

// md
jQuery.fn.fadeToggle = function(speed, easing, callback) {
  return this.animate({opacity: 'toggle'}, speed, easing, callback);  
};

// md
jQuery.fn.slideFadeToggle = function(speed, easing, callback) {
  return this.animate({opacity: 'toggle', height: 'toggle'}, speed, easing, callback);  
};

	jQuery.preloadImages = function()
 {
    for (var i = 0; i < arguments.length; i++)
    {
	   jQuery("<img>").attr("src", location.protocol+'//'+location.host+arguments[i]);
    }
}
$.preloadImages("/assets/images/aboutPage/box_bottom.png", "/assets/images/aboutPage/box_mid.png", "/assets/images/aboutPage/box_top.png", "/assets/images/nav/about_on.png", "/assets/images/nav/about_over.png", "/assets/images/nav/about.png", "/assets/images/nav/availabilities.png", "/assets/images/nav/availabilities_on.png", "/assets/images/nav/availabilities_over.png", "/assets/images/nav/contact.png", "/assets/images/nav/contact_on.png", "/assets/images/nav/contact_over.png", "/assets/images/nav/properties.png", "/assets/images/nav/properties_on.png", "/assets/images/nav/properties_over.png", "/assets/images/nav/sustainability.png", "/assets/images/nav/sustainability_on.png", "/assets/images/nav/sustainability_over.png", "/assets/images/partnerships.png", "/assets/images/partnerships_over.png", "/assets/images/execTeam.png", "/assets/images/execTeam_over.png", "/assets/images/media.png", "/assets/images/media_over.png", "/assets/images/sustainPage/commitment.jpg", "/assets/images/sustainPage/commitment_over.jpg", "/assets/images/sustainPage/one_bryant.jpg", "/assets/images/sustainPage/one_bryant_over.jpg", "/assets/images/sustainPage/four_times.jpg", "/assets/images/sustainPage/four_times_over.jpg", "/assets/images/sustainPage/helena.jpg", "/assets/images/sustainPage/helena_over.jpg", "/assets/images/sustainPage/epic.jpg", "/assets/images/sustainPage/epic_over.jpg", "/assets/images/dfr_on.gif", "/assets/images/dfr_over.gif", "/assets/images/contactPage/submitBtn.png", "/assets/images/contactPage/submitBtn-on.png");


var Durst = {

    init: function(page)
    {
			
        var page = page || 'default';
        this.page = page;
		
        this.navStates('#nav>ul>li');
		this.leftNavOnStates('#left-nav li a');
		
		$('#submitBtn').click(function() {
			$('#pdf').addClass('pdf');
			//$('label.error').css({'textAlign':'left'});
			$('#contact-form').submit();
		});

            jQuery.validator.addMethod("phone",
            function(phone_number, element) {
                phone_number = phone_number.replace(/\s+/g, "");
                return this.optional(element) || phone_number.length > 9 &&
                phone_number.match(/^(1-?)?(\([2-9]\d{2}\)|[2-9]\d{2})-?[2-9]\d{2}-?\d{4}$/);
                //phone_number.match(/^(1-?)?(\([2-9]\d{2}\)|[2-9]\d{2})-?[2-9]\d{2}-?\d{4}$/);
            },
            "Please provide a valid phone number");

            jQuery.validator.addMethod("pdf",
            function(pdf_file, element) {
                pdf_file = pdf_file.replace(/\s+/g, "");
                return this.optional(element) || pdf_file.match(/.pdf$/); // ends with .pdf
            },
            "Attachments must be in pdf format.");

            $("#contact-form").validate();

        // Render UI effects per page
        switch (page) {
        case 'properties':
		
			this.childRollovers('#viewLarge a');
			this.rollovers('#viewAllButton');			
			jQuery.preloadImages = function()
            {
                for (var i = 0; i < arguments.length; i++)
                {
                    jQuery("<img>").attr("src", arguments[i]);
                }
            }
            $.preloadImages("/assets/images/propertySubPages/comm_hdr.png", "/assets/images/propertySubPages/comm_main.jpg", "c/assets/images/propertySubPages/new_dev_hdr.png", "/assets/images/propertySubPages/new_dev_main.jpg", "/assets/images/propertySubPages/prop_map_hdr.png","/assets/images/propertySubPages/res_hdr.png","/assets/images/propertySubPages/res_main.jpg");

            this.aTagOverStates('.pdf>li>a', 'underline', '#2d65b2', 'none', '#000');
            // rollover state for properties left col pdf links
            this.aTagOverStates('.avail>li>a', 'underline', '#2d65b2', 'none', '#000');
            // rollover state for properties left col available space link;
            $('#slideshow_link').click(function() {
                $('#slideImage0').trigger('click');
            });

            // property accordion features
            $(".accordion").accordion({
                animated: "bounceslide",
                collapsible: true,
                activate: true,
                icons: {
                    header: "ui-icon-triangle-1-e",
                    headerSelected: "ui-icon-triangle-1-s"
                }
            });
            $(".accordion_two").accordion({
                animated: "bounceslide",
                collapsible: true,
                active: false,
                icons: {
                    header: "ui-icon-triangle-1-e",
                    headerSelected: "ui-icon-triangle-1-s"
                }
            });
			
            var a = document.URL.split("//");
            // split at protocol
            a = (a[1] ? a[1] : a[0]).split("/");
            path = a[2];
            // use last element of a; split at /
            // host is a[0]; path is a[1..(n-1)]; a[n] is page		
            if (path != '' && path != 'index.php') {
                // must set nav height to auto to fix disappering nav issue in ie6 cause by colorbox script conflict
                if ($.browser.msie && $.browser.version < 7)
                {
                    $('#nav').css({
                        'height': 'auto'
                    });
                    $('.gallery-frame').css({
                        'borderTop': '9px solid #fff'
                    });
					 $('#topImage').css({
                        'borderTop': '9px solid #fff'
                    });
                }
                // lightbox feature
                $("a[rel='imagebox-properties']").colorbox({
					onOpen:function(){ stopSlideShow(); },
					onClosed:function(){ autoSlide(); },
                    transition: 'elastic',
                    speed: 500
                });

            }

            // switches to flash
            $("#viewAllButton").click(function() {
                $('#galleryContainer').hide();
            });
            // switches to flash
            $("#propertyMap").click(function() {
                $('#galleryContainer').hide();
            });

            break;
        case 'sustain':
		 
            jQuery.preloadImages = function()
            {
                for (var i = 0; i < arguments.length; i++)
                {
                    jQuery("<img>").attr("src", arguments[i]);
                }
            }
            $.preloadImages("/assets/images/sustainPage/images/epic_hdr.jpg", "/assets/images/sustainPage/images/helena_hdr.jpg", "/assets/images/sustainPage/images/four_times_hdr.jpg", "/assets/images/sustainPage/images/obp_hdr.jpg", "/assets/images/sustainPage/images/commit_hdr.jpg");

            break;
        case 'about':

            this.linkRollovers('#buttons a');
            // initializing rollovers for buttons within top blue box on home page
            this.aboutNav('.box');

            break;
        case 'contact':
		
			$("#contact-form select").msDropDown();
			$('#filter-form select').msDropDown();
            //this.initCustomSelect('#filter-form select');
			//this.initCustomSelect('#contact-form select');
            this.customCheckboxes('#contact-form input:checkbox');
			
            $('#filter-form select').change(function() {
				$('#filter-form').submit();
            });
			
			$('#clear').click(function() {
				$('#pdf').removeClass('pdf'); // so jquery.validate validation does not turn on until submit is clicked
				$(this).parent().find('label.error').remove(); // for jquery.validate validation
				
                Durst.clearAttachment('pdf');
            });
			
            /* for hr form*/
            this.customFileInput('#pdf');
            // select all checkboxes if all properties is selected on page load
            if ($('.all').attr("checked"))
            {
                $('.property').each(function() {
                    $(this).attr('checked', true);
                });
            }
            break;
        }
    },

    // FUNCTIONS
    initCustomSelect: function(path)
    {
        var inst = this;

        inst.hideSelects = function() {
            $('.custom-select').each(function() {
                $(this).css({
                    zIndex: 8
                }).find('.custom-select-list').hide();
            });
            $(document).unbind('click', inst.hideSelects);
        }

        inst.showSelect = function(e) {
            e.stopPropagation();
            inst.hideSelects();
            var rsel = $(this).parent(),
            list = $(this).parent().find('div.custom-select-list');
            rsel.css({
                zIndex: 1000
            });
            list.css({
                zIndex: 1000
            }).slideDown('fast');
            $(document).bind('click', inst.hideSelects);
        }

        inst.selectOption = function(e) {
            e.stopPropagation();
            var atag = $(this),
            text = atag.text(),
            value = atag.attr('rel'),
            id = atag.attr('target'),
            rsel = $('#custom-select-replaced-' + id);
            $('#custom-select-' + id).text(text);
            $('#' + id).val(value);
            $('#custom-list-' + id).slideUp('fast',
            function() {
                rsel.css({
                    zIndex: 8
                });
                $(this).css({
                    zIndex: 8
                })
            });
            $('#category').trigger('change');

            return false;
        }

        inst.generateCustom = function() {
            var sel = $(this),
            text = this.options[this.selectedIndex].text,
            value = this.options[this.selectedIndex].value,
            id = this.id;
            var s = '<div class="custom-select" id="custom-select-replaced-' + id + '">' +
            '<div class="custom-select-box" id="custom-select-' + id + '" unselectable="on" style="-moz-user-select:none">' + text + '</div>' +
            '<div class="custom-select-list" id="custom-list-' + id + '"><ul class="clearfix">';
            var ops = this.options;
            for (i = 0; i < ops.length; i++) {
                s += '<li><a href="javascript:void(0)" rel="' + ops[i].value + '" target="' + id + '">' + ops[i].text + '</a></li>';
            }
            s += '</ul></div></div>';
            var box = $(s).css({
                marginTop: sel.css('marginTop'),
                marginBottom: sel.css('marginBottom')
            });
            sel.after(box).hide();
            return box;
        }

        $(path).each(function() {
            var box = inst.generateCustom.call(this);
            box.find('div.custom-select-list>ul>li>a').click(inst.selectOption);

            box.find('div.custom-select-box').click(inst.showSelect);
        });
    },

    customFileInput: function(path)
    {
        var customWidth = 406;
        var customHeight = 20;

        $(path).each(function() {
            var inputField = $(this);

            var d = $('<div>'),
            d2 = $('<div style="position: relative;height:20px;width:406px;"></div>'),
            d3 = $('<div class="filename" style="overflow:hidden;white-space:nowrap;width:324px;height:17px;line-height:18px;padding:0px 3px 3px 5px;position:absolute;left:0;top:0; "></div>');
            inputField.css({
                height: customHeight,
                width: customWidth,
                opacity: 0,
                zIndex: 8
            });
            inputField.before(d2);
            d.css({
                position: 'absolute',
                zIndex: 5,
                left: 0,
                top: 0,
                width: customWidth,
                height: customHeight,
                background: 'url(/assets/images/contactPage/attach.png) no-repeat'
            });
            d2.append(d.append(d3, inputField));
            d3.text(this.defaultValue.split(/\/|\\/).pop());
            // display visible text based upon input field value on page load
            inputField.prev('.filename').text(this.value.split(/\/|\\/).pop());
            inputField.change(function() {
                // display visible text based upon input field value on change
                $(this).prev('.filename').text(this.value.split(/\/|\\/).pop());
				
            });
        });

    },
		
	clearAttachment:function(id)
	{
		var $id = $('#'+id);
		$id.prev('.filename').text('');
		var elem = document.getElementById(id);
		parentDiv = elem.parentNode;
		newDiv=document.createElement('div');
		newDiv.innerHTML= parentDiv.innerHTML;
		outerNode = parentDiv.parentNode;
		outerNode.replaceChild(newDiv,parentDiv);
		Durst.customFileInput('#contact-form input:file');
	},
	
    // Create custom checkboxes using image replacement
    customCheckboxes: function(path)
    {
        var doCheck = function(preload) {
            var el = this;
            var src = el.tagName;
            var img = el.tagName == 'INPUT' ? $(el).next('img').get(0) : el;
            var inp = el.tagName == 'IMG' ? $(el).prev('input').get(0) : el;
            var label = $(el).parent().find('label');

            if (src == 'IMG') {
                img.src = inp.checked ? '/assets/images/contactPage/checkoff.gif': '/assets/images/contactPage/checkon.gif';
                inp.checked = inp.checked ? false: true;

            } else {
                img.src = inp.checked ? '/assets/images/contactPage/checkon.gif': '/assets/images/contactPage/checkoff.gif';
            }

            inp.checked ? label.css({
                'color': '#2d65b2'
            }) : label.css({
                'color': '#4c4c4c'
            });
        }

        $(path).each(function() {
            var d = $('<img src="/assets/images/contactPage/checkoff.gif" width="8" height="8" class="checkbox" />');
            d.bind('doCheck', doCheck).click(function(e) {
                $(this).trigger('doCheck');
            })
            .bind('focus',
            function() {
                $(this).addClass('focus')
            })
            .bind('blur',
            function() {
                $(this).removeClass('focus')
            })
            .bind('keypress',
            function(e) {
                if (e.keyCode != 9) $(this).trigger('click')
            });

            var css = {
                position: 'absolute',
                opacity: 0
            };

            // Firefox 2 can't handle opacity over flash			
            /*if($.browser.firefox2()){
				css = {position:'absolute',zIndex:-1,width:1};
			}*/

            $(this).click(doCheck).css(css).after(d);
            doCheck.call(this);
        });
        // if all properties is clicked check all checkboxes, if it is unchecked uncheck all checkboxes
        $('.all').click(function() {
            if ($(this).is(':checked'))
            {
                $('.property').each(function() {
                    this.checked = false;
                    $(this).next('img').trigger('doCheck');
                });
            }
            else
            {
                $('.property').each(function() {
                    this.checked = true;
                    $(this).next('img').trigger('doCheck');
                });
            }
        });
		
		// if all properties is checked on page load check all checkboxes
        if ($('.all').is(':checked'))
        {
            $('.property').each(function() {
                
				this.checked = false;
                $(this).next('img').trigger('doCheck');
            });
        }
       /* else
        {
            $('.property').each(function() {
                this.checked = true;
               $(this).next('img').trigger('doCheck');
            });
        }*/

        $('.property').each(function() {
            // uncheck all properties box if all checkboxes are not checked
            $(this).click(function() {
                if (! ($(this).is(':checked')))
                {
                    if ($('.all').is(':checked'))
                    {
                        $('.all').checked = false;
                        $('.all').next('img').trigger('doCheck');
                    }
                }
                // check all properties box if all checkboxes are not checked
                if ($('.property:checked').length == $('.property').length)
                {
                    if (! ($('.all').is(':checked')))
                    {
                        $('.all').checked = true;
                        $('.all').next('img').trigger('doCheck');
                    }
                }
            });
        });
    },

    navStates: function(b)
    // b is the id of the li tag - controls over states and dropdowns for top nav - on states are controlled separately inside the doc ready
    {
        //nav over states
        $(b).hover(
        function() {
            aTag = $(this).find('a:first');
            origUrl = aTag.css('backgroundImage');
            bkrdUrl = aTag.css('backgroundImage');
            // orginial value of bkrdUrl- will change
            if (origUrl.match(/_on.png/))
            {
                bkrdUrl = origUrl.split("_on.png").join(".png");
            }
            else if (origUrl.match(/_over.png/))
            {
                bkrdUrl = origUrl.split("_over.png").join(".png");
            }

            aTag.css('backgroundImage', bkrdUrl.split(".png").join("_over.png"));
            $(this).find('ul').css('display', 'block');
        },
        function() {

            if (bkrdUrl.match(/_on.png/))
            {
                aTag.css('backgroundImage', origUrl.split("_over.png").join("_on.png"));
            }
            else
            {
                aTag.css('backgroundImage', origUrl.split("_over.png").join(".png"));
            }
            $(this).find('ul').css('display', 'none');
        });
        //nav on states
        var a = document.URL.split("//");
        // split at protocol
        a = (a[1] ? a[1] : a[0]).split("/");
        subd = a[1];
        // use last element of a; split at /
        // host is a[0]; path is a[1..(n-1)]; a[n] is page		
        if (subd == 'properties') {
            $('#nav ul li a.properties').parent().addClass('on');
        } else if (subd == 'availabilities') {
            $('#nav ul li a.availabilites').parent().addClass('on');
        } else if (subd == 'about') {
            $('#nav ul li a.about').parent().addClass('on');
        } else if (subd == 'sustainability') {
            $('#nav ul li a.sustainability').parent().addClass('on');
        } else if (subd == 'contact') {
            $('#nav ul li a.contact').parent().addClass('on');
        }
    },

    aTagOverStates: function(aTag, onTextStyle, onTextColor, offTextStyle, offTextColor)
    //uses 'a' tag w/ parent tag's background image changing on hover
    {
        $(aTag).hover(
        function() {
            parentTag = $(this).parent();
            //alert(parentTag.get(0).tagName);
            bkrdUrl = parentTag.css('backgroundImage');

            parentTag.css('backgroundImage', bkrdUrl.split(".png").join("_over.png"));
            $(this).css({
                'textDecoration': onTextStyle,
                'color': onTextColor
            });
        },
        function() {
            parentTag.css('backgroundImage', bkrdUrl.split("_over.png").join(".png"));
            $(this).css({
                'textDecoration': offTextStyle,
                'color': offTextColor
            });
        });
    },
    linkRollovers: function(a)
    // id of a tag
    {
        $(a).hover(
        function() {
            bkrdUrl = $(this).css('backgroundImage');
            $(this).css('backgroundImage', bkrdUrl.split(".png").join("_over.png"));
        },
        function() {
            $(this).css('backgroundImage', bkrdUrl.split("_over.png").join(".png"));
        });
    },

    aboutNav: function(box)
    // id of container tag
    {
        //nav on states
        var a = document.URL.split("//");
        // split at protocol
        a = (a[1] ? a[1] : a[0]).split("/");

        $('#layoutA-nav a').each(function() {
            aboutPath = (a[2]);
            aboutPath = aboutPath.slice(0, -4);
            aboutNavId = $(this).attr("id");
            bkrdUrl = $(this).css('backgroundImage');
            if (aboutPath == aboutNavId)
            {
                $(this).css('backgroundImage', bkrdUrl.split(".jpg").join("_on.jpg"));
            }
        });
        //nav rollovers
        $(box).hover(
        function() {
            aTagId = $(this).find('a').attr('id');
            $(this).find('.about-over').css({
                'display': 'block'
            });
            $(this).click(function() {
                location.href = "/about/" + aTagId + ".php";
            });
        },
        function() {
            $(this).find('.about-over').css({
                'display': 'none'
            });
        });
    },

    rollovers: function(b)
    // b is the id of the img tag
    { 
        $(b).mouseenter(
        function() {
            $(this).attr('src', $(this).attr("src").split(".").join("-over."));
			//alert($(this).attr("src"));
        }).mouseleave(
        function() {
            $(this).attr('src', $(this).attr("src").split("-over.").join("."));
			//alert($(this).attr("src"));
        });
    },
	 childRollovers: function(b)
    // b is the id of the img tag
    { 
        $(b).mouseenter(
        function() {
			image = $(this).find('img');
            image.attr('src', image.attr("src").split(".").join("-over."));
			
			//alert($(this).attr("src"));
        }).mouseleave(
        function() {
           image.attr('src', image.attr("src").split("-over.").join("."));
			//alert($(this).attr("src"));
        });
    },

     leftNavOnStates: function(tag)  
	 {
	 $(tag).each(
		function() {
	
			var a = window.location.href.split("//");
			// split at protocol
			a = (a[1] ? a[1] : a[0]).split("/");
			path = a[2];
			var re = new RegExp(path.replace("?", "\\?"), 'i');	
			var reGet = /\?/;
			if (path != '' && !(reGet.test(path))) // if path doesn't contain a ? match only attr's without ?'s
			{
				if (re.test($(this).attr('href')) && !(reGet.test($(this).attr('href'))) ) {					
					$(this).addClass('current');
				}
			}
			else if (path != '') 
			{
				if (re.test($(this).attr('href')) ) {					
					$(this).addClass('current');
				}
			}			
		});
	 }

}






