
(function ($){
    var appControl = $.extend(new Object(),{
        hashURLs : function (){
            var self = this;
            $('body').find('a').not('.rich-text a').each(function (){
                var a = $(this).attr('href');
                if (!a) {return true;}
                if (!a.match(/#/)) {
                    $(this).attr('href','/#'+a);
                    $(this).click(function (){
                        self.navdelta.apply(self,[$(this)]);
                    });
                }
            });
        },
        init : function (){
            var self = this;
            this.hash = '';
            this.timer = setInterval(function (){self.watch.apply(self);}, 200);
            this.hashURLs();
            this.footer.init();
                $('#reveal').click(this.footer.toggle);
            var item = $('#nav ul li.parent');
                item.find('ul.subnav-ul').hide();
            this.home = !window.location.hash.match(/#\/.+/);
            // if (!this.home) {$('#logo #text div').css('left','-400px');}
            
            // $.ajaxSettings.cache = false;
            
            return this;   
        },
        watch : function (){
          var url = window.location.hash,
          self = this,
          // a = '/a/'+url.slice(2);
          a = url.slice(2)+'?ajax';
          if (url != this.hash) {

              $('#content').fadeOut('slow', function (){
                  if (a == '/') {a = '/?ajax';}
                  window.RSD.slugNameSpace = a.match(/project=/) ? a.match(/project=[a-z0-9-]+/i)[0].replace(/project=/,'') : false;
                  if ( a.match(/project=[a-z0-9-]+/i) ) {
                      a = a.replace(/project=\S+\?/, '?');
                  }
                  $(this).load(a , function (data, status, request){
                      if (parseInt(request.status, 10) !== 200) {
                          $(this).load('/404?ajax', function(){
                              self.ishome();
                              if(!window.RSD.slugnameSpace){
                                  $('#content').fadeIn();  
                                  window.resizeBackground();                    
                              }
                          });
                      }
                  self.ishome();
                  if(!window.RSD.slugnameSpace){
                      $('#content').fadeIn();  
                      window.resizeBackground();                    
                  }
                  });
              });
          }
          this.hashURLs(); 
          this.hash = url;  
        },
        navdelta : function (item) {

            if (item.closest('li').hasClass('parent')) {
                item.siblings('ul.subnav-ul').slideDown('slow').find('a').removeClass('subnavselected');
                item.parent().siblings().find('ul.subnav-ul').slideUp('slow').parent().parent().find('a.selected').removeClass('selected');
                item.addClass('selected');
                var url = item.find('a').attr('href');
                if (item.parent().is('#nav-our-work')) {
                   this.ourwork.growline();
                   $('a.subnavselected').removeClass('subnavselected');
                } else {
                    this.ourwork.resetline();
                    if (item.siblings('ul.subnav-ul')){
                        item.siblings('ul').find('li').eq(0).find('a').addClass('subnavselected');
                    }
                }

            
            }

            if (item.hasClass('subnav')){
                item.parent().siblings().children('a.subnavselected').removeClass('subnavselected');
                item.addClass('subnavselected');
            }
            return item;
        },
        ourwork : {
            growline : function (){
                $('li#nav-our-work a').animate({'width':'970px'},1000);
            },
            resetline : function (){
                $('li#nav-our-work a').css('width','100px');
            }
        },
        ishome : function (){
            var navs = $('ul.subnav-ul'),
            bgc = $('#bg-changer');
            if (this.home === false && $('#you-are-home').size()) {
                navs.slideUp();   
                // this.logo.open();     
                this.home = true;
                bgc.animate({top:0},666); 
                $('#nav ul').find('a.selected').removeClass('selected');
                window.RSD.bg.play();    
            } else if (this.home === false && !$('#you-are-home').size()) {
                // this.logo.close();
                this.home = false;
                bgc.css('top',-18);
                window.RSD.bg.pause();  
            } else if (this.home === true && $('#you-are-home').size()) {
                this.home = false;
                window.RSD.bg.play();    
            } else if (this.home === true && !$('#you-are-home').size())  {
                this.home = false;
                // this.logo.close();
                bgc.animate({top:-18},666);
                window.RSD.bg.pause();  
            }
        },
        logo : {
          open : function (){
              var text = $('#logo #text div');
              text.animate({'left':'0'},666);
              return true;
          },
          close : function (){
              var text = $('#logo #text div');
              text.animate({'left':'-400px'},666);
              return true;
          }
        },
        footer : {
            hidden : false,
            init : function (){
                $('#footer').css({bottom:-$('#footer').height()});
                hidden = true;
            },
            toggle : function (){
                var f = $('#footer'),
                r = $('#reveal');
                if (hidden === true) {
                    f.animate({bottom:0},1000);
                    r.animate({width:'18px'},1000);
                    r.html('<span class="darr">&darr;</span>');
                    hidden = false;
                } else {
                    f.animate({bottom:-f.height()},1000);
                    r.animate({width:'144px'},1000);
                    r.html('<span>&#43;</span> Connect with RSA');
                    hidden = true;
                }
            }
        }
    });
    var galControl = $.extend(new Object(),{
        init : function (){
            
            function textToggle () {
                $('span.open').live('click', function (){
                    $('#content .text').slideDown(666);
                    $('#list-grid').animate({'margin-top':'0'},666);
                    $('span.open').fadeOut('slow');
                });
                $('span.close').live('click', function (){
                    $('#content .text').slideUp(666);
                    $('#list-grid').animate({'margin-top':'18px'},666);
                    $('span.open').fadeIn('slow');
                });
            }
            textToggle();
            return this;
        },
        detailView : function (){

            var self = this;
            var name = $('td.category-identifier').attr('rel');
            $('a.subnavselected').removeClass('subnavselected');
            $('li#nav-'+name).find('a').addClass('subnavselected');

            var project_thumbs = function (){
                var thumbs = $('.thumb-container .thumb img'),
                    count = thumbs.length,
                    next = $('.controls .right'),
                    previous = $('.controls .left'),
                    con = $('.imgbox').addClass('rich-text');
                if (count > 5) { 
                    $('.controls .right').removeClass('inactive');
                    var self = this,
                        box = $('.thumb-container');
                    project_thumbs.current = 0;
                    this.rotate = function (){
                        box.animate({'left':project_thumbs.current+'px'},666);
                        self.check();
                    };
                    this.check = function (){
                        if (project_thumbs.current < 0) {previous.removeClass('inactive');} else {previous.addClass('inactive');}
                        if (project_thumbs.current <= -count*40) {next.addClass('inactive');} else {next.removeClass('inactive');}
                    };
                    next.click(function (){
                        if ($(this).hasClass('inactive')){return false;}
                        this.tomove = (count/5 > 2) ? 5 : (count % 5);
                        project_thumbs.current -= 90*this.tomove; 
                        self.rotate();
                    });
                    previous.click(function (){
                        if ($(this).hasClass('inactive')){return false;}
                        this.tomove = (count/5 > 2) ? 5 : (count % 5);
                        project_thumbs.current += 90*this.tomove;
                        self.rotate();
                    });
                }
                
              
                thumbs.each(function(i, tem){                    
                  var kore = $(tem),
                  img = $('<img />').load(function (){
                      $(this).fadeIn();
                      }).css({position:'absolute', top:'0px', left:'0px', 'z-index':30, 'cursor':'pointer'})
                    .appendTo(con)
                    .hide()
                    .attr('src', kore.attr('src')).attr('rel', kore.attr('rel')).attr('alt', kore.attr('alt')).end().show();
                    

                    
                      kore.parent().css({'position':'absolute','left':(90*i)});
                      kore.click(function (e){
                        e.preventDefault();
                        store_swap_image(i);
                      });
                      if(i===0) {img.css('z-index', 40);}
                    });

                };
                $('#internal-nav a.frame').each(function (i){
                    $(this).css('opacity',0.3).hover(function (){
                        this.left = i === 0 ? 0 : 648;
                        $(this).stop().animate({
                            'width' : 466,
                            'left' : i === 0 ? 0 : 324,
                            'opacity' : 1.0
                        },666);
                        $(this).find('.info').fadeIn();
                    }, function (){
                        $(this).stop().animate({
                            width: 142,
                            left: this.left,
                            opacity: 0.5
                        },666, function (){
                            $(this).find('.info').fadeOut(); 
                        });
                    });
                });

              var store_swap_image = function (n){
                $('.imgbox img:eq('+n+')').css('z-index',40).siblings('img').css('z-index',30);
              };
          
             project_thumbs();
              
             var imgIndex;
             
             var caption_text = '';
             var caption_html = '';
            
             /**
              * Adjusts the position of the lightbox
              */
             function adjustTop() {
                 $('#project-lightbox-wrap').css('top', $(window).scrollTop());
             }

             $('.imgbox img').click(function(){
                adjustTop();
                // $('#project-lightbox').html('');
                imgIndex = $(this).index();
                //console.log('imgIndex= '+imgIndex);
                // $('#project-lightbox').css({
                //      width : 0,
                //     "border-width" : "1px"
                // });
                var htmlString = '';
                var captionString = '';
                $('.imgbox img').each(function(index) {
                   larger_url = $(this).attr('rel');
                   alt_text = $(this).attr('alt');
                   htmlString += '<img src="'+larger_url+'" alt="'+alt_text+'"/>';
                   
                   
                   // $('#project-lightbox').append('<img src="'+larger_url+'"/>');
                });
                $('#project-lightbox img').replaceWith(htmlString);                
                $('#project-lightbox img:eq('+imgIndex+')').show(function() {
                    plbWidth = $('#project-lightbox img:eq('+imgIndex+')').width();
                    plbHeight = $('#project-lightbox img:eq('+imgIndex+')').height();
                    $('#project-lightbox').width(plbWidth);
                    // $('#project-lightbox').animate({
                    //         width : plbWidth
                    //     }, 1000);
                    // $('#project-lightbox').animate({
                    //         "border-width" : "18px"
                    //     }, 1000);
                });
                $('#project-lightbox, #lightbox-controls, #project-lightbox-wrap, #opacity-div').show();
                
                caption_text = $('#project-lightbox img:eq('+imgIndex+')').attr('alt');
                caption_html = '<div class="caption">'+caption_text+'</div>';
                $('#lightbox-controls .caption').replaceWith(caption_html);
                
                $('#project-lightbox-wrap, #opacity-div').width($('#grid').width());
                
                // $('#lightbox-controls').width(plbWidth).css("top", (plbHeight + 66));

             });
             
             // On wrap or close click, hide all
             $('#opacity-div, #lightbox-close .lb-close').click(function(){
                 $('#project-lightbox').fadeOut();
                 $('#lightbox-controls, #project-lightbox-wrap, #opacity-div').hide();
             });

            //next
             $('#lightbox-controls .right').click(function() {
                adjustTop();
                $('#project-lightbox img:eq('+imgIndex+')').hide();
                imgIndex = imgIndex + 1;
                imgCount = $('#project-lightbox img').size();
                if(imgIndex >= imgCount ){
                	imgIndex = 0;
                }
                
                plbWidth = $('#project-lightbox img:eq('+imgIndex+')').width();
                $('#project-lightbox').animate({
                        width : plbWidth
                    }, 250);
                
                caption_text = $('#project-lightbox img:eq('+imgIndex+')').attr('alt');
                caption_html = '<div class="caption">'+caption_text+'</div>';
                $('#lightbox-controls .caption').replaceWith(caption_html);
                
                $('#project-lightbox img:eq('+imgIndex+')').fadeIn();
                adjustTop();
             });
             
             //prev
              $('#lightbox-controls .left').click(function() {
                 $('#project-lightbox img:eq('+imgIndex+')').hide();
                 imgIndex = imgIndex - 1;
                 imgCount = $('#project-lightbox img').size();
                 if(imgIndex <= - 1 ){
                 	imgIndex = imgCount - 1;
                 }

                 plbWidth = $('#project-lightbox img:eq('+imgIndex+')').width();
                 $('#project-lightbox').animate({
                         width : plbWidth
                     }, 250);

                 caption_text = $('#project-lightbox img:eq('+imgIndex+')').attr('alt');
                 caption_html = '<div class="caption">'+caption_text+'</div>';
                 $('#lightbox-controls .caption').replaceWith(caption_html);
                 
                 $('#project-lightbox img:eq('+imgIndex+')').fadeIn();
                 adjustTop();
              });
              
              setInterval(function(){$('#opacity-div').height($('#grid').height())}, 250);     
              
              

             
        },
       
        
        gridObject : function (item){
            var self = this;

            this.views = function (){
                $('ul#views li a').each(function (i){
                    var item = $(this),
                    pos = -(i*808);
                    item.click(function (){
                        $('#list-grid').stop({clearQueue:true}).animate({'left':pos},666);
                    });
                });

            };
            
            
            this.init = function (){
                var i = item.index,
                mod = i % 5;
                frame = $('<a></a>')
                .attr('href',item.href)
                .addClass('frame')
                .css({ top : (Math.floor(i/5) * 162) , left : (i % 5) * 162 })
                
                .append('<div></div>')
                            // .append("<img src='"+item.longimg+"' alt='"+item.title+"'/><div class='info'><a href='"+item.href+"'><span class='category'>"+item.category+"</span><span class='arrow'>&rarr;</span><span class='name'>"+item.title+"</span></a></div>");
                            .append("<img src='"+item.longimg+"' alt='"+item.title+"'/><div class='info'><span class='category'>"+item.category+"</span><span class='arrow'>&rarr;</span><span class='name'>"+item.title+"</span></div>");
                $('#container').append(frame);

                var imgwidth = 466,
                    info = frame.find('div.info'),
                    showinfo = function (){
                        info.fadeIn();
                    },
                    hideinfo = function (){
                        info.fadeOut();
                    };
                
                if (mod === 0) {
                    frame.hover(function (){
                        $(this).stop().animate({
                            'width' : imgwidth
                        },666, showinfo()).css('z-index', 10);
                    }, function (){
                        hideinfo();
                        $(this).stop().css('z-index',9).animate({
                            width: 142
                        },666, function (){$(this).css('z-index', 1); });
                    });
                } else if (mod === 4) {
                    frame.hover(function (){
                        $(this).stop().animate({
                            'width':imgwidth,
                            'left': 324
                        }, 666, showinfo()).css('z-index', 10);
                    }, function (){
                        hideinfo();
                        $(this).stop().css('z-index',9).animate({
                            'width': 142,
                            'left': 648
                        }, 666, function (){$(this).css('z-index', 1);});
                    });
                } else {
                    var ol = parseInt(frame.css('left'), 10);
                    frame.hover(function (){
                        $(this).stop().animate({
                            'width':466,
                            'left': ol-162
                        }, 666, showinfo()).css('z-index','10');
                    }, function (){
                        hideinfo();
                        $(this).stop().css('z-index',9).animate({
                            'width':142,
                            'left': ol
                        }, 666).css('z-index',1);
                    });
                }

                this.views();
            };
        },
        listToGrid : function (){
            var proj = $('ul.list-view li'),
            all = [];
            $('#list-grid');
            
            proj.each(function (i, item){
                var item = $(item),
                    info = {
                        title : item.find('h2 a').text(),
                        image : item.find('.thumb img').attr('src') 
                    };
                $(item).find('.project-details dl').each(function (i, item){
                    info[this.className.split(' ')[0]] = $(this).find('dd').text();
                });
                
                all[i] = info;
            });
            for (i=0;l=all.length,i<l;i++){
                var item = all[i],
                    newgrid;
                item.index = i;
                newgrid = new this.gridObject(item);
                newgrid.init();
            }
            $('#list-container').css('left','808px');
            this.makeMap();
        },
        makeMap : function (){
            // river-st-architecture.com key = ABQIAAAAnvt8wAG-lGbpsZBbKr28yBRZHlv5cqUd4N0q2sG7o1TP1IPSrxRmQaksM6KuEcExRGbEhJraUk1yfQ
            var self = this;

            // This function is called when $.getScript completes
            window.mapLoaded = function (){
                window.mapLoaded = null;
                $.getScript("http://gmaps-utility-library.googlecode.com/svn/trunk/markermanager/release/src/markermanager.js", function(){
                    $.getScript("/media/js/extinfowindow.js", function(){
                        

                     // Instantiate Google Map
                    var map = new GMap2(document.getElementById("map_canvas")),
                    bounds = new GLatLngBounds();
                    map.setCenter(new GLatLng(35.035844, -85.3066006), 13);
                    map.setUIToDefault();
                    map.enableContinuousZoom();

                    // Get JSON objects from server
                    $.getJSON('/get-all', 
                        function (data, textStatus){
                            // Select only objects with a geocode property
                            var locations = _.select(data, function (loc){return loc.geocode;}),
                            categories = _.uniq(_.flatten(_.pluck(data, 'categories'))),
                            projects = _.flatten(_.pluck(data, 'slug')),
                            // current = window.location.hash.slice(2).replace('projects/','');
                            current = window.RSD.slugNameSpace ? window.RSD.slugNameSpace : window.location.hash.match(/([a-z-])+$/)[0];
                            
                            var baseIcon = new GIcon(G_DEFAULT_ICON);
                                baseIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";
                                baseIcon.iconSize = new GSize(30, 40);
                                baseIcon.shadowSize = new GSize(0, 0);
                                baseIcon.iconAnchor = new GPoint(12, 40);
                                baseIcon.infoWindowAnchor = new GPoint(9, 2);
                            
                            var iconImages = {};

                            // Create Markers for each object
                            $(locations).each(function (){
                                var self = this;
                                this.category = this.categories[0] || false;
                                this.customicon = new GIcon(baseIcon) || false;
                                this.customicon.image = "../media/images/"+this.category+"_icon.png" || false;
                                this.geocode = _(this.geocode.split(', ')).toArray() || false;
                                this.point = new GLatLng(this.geocode[0], this.geocode[1]) || false;
                                this.marker = new GMarker(this.point, this.customicon) || false;
                                bounds.extend(this.marker.getPoint());
                                this.content = '<div class=\'marker-text\'>\
                                                    <div class="'+this.category+'"\
                                                        <img src="'+this.thumb+'"></img>\
                                                        <h1><a href="'+this.href+'">'+this.title+'</a></h1>\
                                                        <table class=\'first\'>\
                                                            <tr id=\'location\'>\
                                                                <td class=\'label\'>Location</td>\
                                                                <td>'+this.address+'</td>\
                                                            </tr>\
                                                        </table>\
                                                        <table class=\'second\'>\
                                                            <tr>';
                                    if (this.year_built){
                                        this.content += '<td class=\'label year-completed\'>Year Completed</td>\
                                                        <td>'+this.year_built+'</td>';
                                    }
                                    if (this.build_cost){
                                        this.content += '<td class=\'label build-cost\'>Build Cost</td>\
                                        <td>'+this.build_cost+'</td>';
                                    }
                                    
                                    this.content += '</tr>\
                                                        </table>\
                                                        <a href="'+this.href+'" class=\'view-project\'>View Project</a>\
                                                    </div>\
                                                </div>';                     
                                                            
                                this.bubble = $(this.content);
                                
                                GEvent.addListener(this.marker, 'click', function (){
                                    self.marker.openExtInfoWindow( map, "project_bubble", self.bubble.html(), false);
                                });

                                map.addOverlay(this.marker);
                                this.marker.hide();

                                if (current == 'projects') {
                                    this.marker.show();
                                } else if ( _.include(this.categories, current) ){
                                    this.marker.show();
                                } else {return true;}

                            });

                            if (current == 'projects') {
                                $('.key li a').addClass('visible');
                            } else if (_.include(projects, current.toString())) {
                                // This is if current is equal to a project's slug
                                $('.text').hide();
                                var what = _.select(locations, function(z){
                                    return z.slug === current.toString();
                                })[0];
                                $('#list-grid').css('left','-1616px');
                                what.marker.show();
                                map.setCenter(what.point);
                                $('#content').fadeIn(); 
                            
                                
                            } else {
                                $('.key li.'+current+' a').addClass('visible');
                                map.panTo(bounds.getCenter());
                            }

                            $('.key li').each(function (){
                                var self = this;
                                this.slug = $(this).closest('li').attr('class');
                                if (current=='projects') {this.isVisible = true;} else if (current == this.slug ) {this.isVisible = true;};
                                if (this.isVisible === true) {
                                    $(this).closest('li').addClass('visible');
                                }
                                this.projects = _.select(locations, function (p){
                                    return _.include(p.categories, self.slug);
                                });

                                $(this).click(function (e){e.preventDefault();
                                    map.panTo(bounds.getCenter());
                                    if (!this.isVisible){
                                        _.each(this.projects, function (p){p.marker.show();});
                                        this.isVisible = true;
                                        $(this).addClass('visible');
                                    } else {
                                        _.each(this.projects, function (p){p.marker.hide();});
                                        this.isVisible = false;
                                        $(this).removeClass('visible');
                                    }
                                });
                            });
                        });
                    });                    
                });
 
            };
            this.key = 'ABQIAAAAnvt8wAG-lGbpsZBbKr28yBT2yXp_ZAY8_ufC3CFXhHIE1NvwkxSZn8cjZJlSFFocurMjDClAlEXZRw';
            this.getKey = function(){
                var site = window.location.hostname;
                if (site === 'localhost') {return 'ABQIAAAAnvt8wAG-lGbpsZBbKr28yBT2yXp_ZAY8_ufC3CFXhHIE1NvwkxSZn8cjZJlSFFocurMjDClAlEXZRw'}
                else if (site === '192.168.0.122') {return 'ABQIAAAAnvt8wAG-lGbpsZBbKr28yBRvTJz_4Zm3VEVivlxSqxVFnd1C-RRHdH6FIr-KZUBlwWqVqMBeoO__SA'}
                else if (site === 'riverstreetarchitecture.com.hdev.thisismedium.com') {return 'ABQIAAAAnvt8wAG-lGbpsZBbKr28yBTWQgg9FGbvMK85O-GHTYsoU3UP9xQW3AQkjohLywQjxlnnipeuKXIJ5g'}
                else if (site === 'riverstreetarchitecture.com') {return 'ABQIAAAAnvt8wAG-lGbpsZBbKr28yBTWTL3S1kz4lHvHC2skW-TPLHlDQhTNKh70QPErBnE9e_y5UCj_kB3IfQ'}
                else {return 'ABQIAAAAnvt8wAG-lGbpsZBbKr28yBRvTJz_4Zm3VEVivlxSqxVFnd1C-RRHdH6FIr-KZUBlwWqVqMBeoO__SA';};
            };
            jQuery.getScript("http://maps.google.com/maps?file=api&v=2&sensor=false&async=2&callback=mapLoaded&key="+this.getKey());
        }
    });
    var bgControl = $.extend(new Object(),{
        init : function (){
            var self = this,
            item = $('#bg-changer ul li.work'),
            infoBox = $('#infoBox');
            this.bin = [];
            this.current = parseInt(this.bin.length -1, 10);
            this.timer = false;
            infoBox.css({top:'-18px','overflow':'hidden','width':'0'});
            item.each(function (i){
                var kore = this;
                this.name = $(this).find('ul').attr('class');
                this.cat = $(this).find('li.cat').text();
                this.img = $(this).find('li.img').text();
                this.title = $(this).find('li.title').text();
                this.link = $(this).find('li.title a').attr('href');
                this.catlink = $(this).find('li.cat a').attr('href');
                self.bin[i] = 'photo-'+i;
                $(this).addClass('photo-'+i);
                $('ul#bg').append($('<li id="photo-'+i+'" class="gal"><img src="'+this.img+'" alt="'+this.title+'"/></li>'));
                $(this).click(function (){
                    var right = 990 - $(this).offset().left;
                    infoBox.find('.cat a').text(kore.cat).attr('href', kore.catlink);
                    infoBox.find('.title a').text(kore.title).attr('href', kore.link);
                    infoBox.css({'top':'0px','right': right,'width':'0'});
                    infoBox.stop().animate({'width':'275px'},666);
                    self.rotate(i);
                    clearInterval(self.go);
                    self.go = setInterval(function (){
                        self.rotate.call(self);
                    }, 6666);
                    $(this).mouseOut(function(){
                        $(this).stop();
                        boxClose();
                    });
                }, function (){
                    self.timer = setTimeout(boxClose, 50);
                });
            });
            var boxClose = function (){
                infoBox.stop().animate({'width':'0px'},666,function (){$(this).css('top','-18px')});
            };
            infoBox.hover(function (){
                clearTimeout(self.timer);
                self.timer = false;
            }, function (){
                boxClose();
            });
            return this;
        },
        color : function (colorkey){ // This function is called on pages in Our Work by a callback in the <body>
            if(colorkey){
                var color = colorkey.color ? colorkey.color.match(/^#/) ? colorkey.color : colorkey.color = "#"+colorkey.color : false,
                image = colorkey.image ? colorkey.image : false,
                colorize = {
                    make_default : function () {
                        this.default_color = "#324745";
                        $('#footer').css({'background-color': this.default_color})
                        $('#reveal').css('background-color', this.default_color)
                        if (window.ie){
                            $('.color-bg').css(
                                {'background-color': this.default_color,
                                 'background-image': 'url(/media/images/grid.png)',
                                 'background-position': '0 0',
                                 'background-repeat': 'repeat'
                                })
                        }
                        
                    },
                    make_transparent : function () {
                        var color = $('body').css('background-color')
                        $('#footer').css({'background-color': this.darken(color, 0.8)})
                        $('#reveal').css('background-color', this.darken(color, 0.8))
                        if (window.ie){
                            $('.color-bg').css(
                                {'background-color': this.darken(color, 0.8),
                                 'background-image': 'url(/media/images/grid.png)',
                                 'background-position': '0 0',
                                 'background-repeat': 'repeat'
                                })
                        }

                        $('span.open').css('background-color', this.darken(color, 0.8))
                    },
                        darken : function(c, v) {
                            var rgb;
                            if (/^rgb/.test(c)) {
                                rgb = _.map(c.match(/\((\d+), ?(\d+), ?(\d+)\)/).slice(1), function(num){ return parseInt(num, 10); });
                            } else if (/^#/.test(c)) {
                                rgb = _.map(c.match(/^#([a-f0-9]{2})([a-f0-9]{2})([a-f0-9]{2})/i).slice(1), function(num){ return parseInt(num, 16)})
                            } else return 'bad color type';
                        var x = _.map(rgb, function(c) { return Math.floor(v*c) })    
                        return 'rgb('+x.join(',')+')';
                    }
                };
                $('body').css('background-color',color);
                if (image) {
                    colorize.make_default();
                    var tbi = $('li#single-page-bg'),
                        newimg = $("<img src='"+image+"'>");
                    tbi.append(newimg).find('img').fadeIn('fast').siblings('img:last').fadeOut('slow', function (){
                        $(this).remove();
                    }).end().css({
                        'left':'0',
                        'top':'0'
                    });
                } else if (color) {
                    $('li#single-page-bg').find('img').fadeOut('slow', function (){
                        $(this).remove();
                    });
                    colorize.make_transparent();
                } else {
                    colorize.make_default();  
                }
            }
            return this;
        },
        rotating : false,
        play : function (){
            var self = this;
            this.rotating = true;
            this.rotate();
            this.go = setInterval(function (){
                self.rotate.call(self);
            }, 6666);
            return true;
        },
        pause : function (){
            clearInterval(this.go)
            this.rotating = false;
            $('ul#bg').find('li.gal img').fadeOut('slow');
            return true;
        },
        rotate : function (clicked){
            if (clicked === this.current) {return true;}
            var bg = $('ul#bg'),
                changer = $('div#bg-changer ul'),
                i = this.current,
                j = i === this.bin.length -1 ? 0 : i+1;
            if(clicked){j = clicked, this.current = j-1}
            toShow = bg.find('li#photo-'+j).find('img'),
            toHide = bg.find('li#photo-'+i).find('img');
    
            
            toShow.fadeIn('slow', function (){
                toHide.fadeOut();
            }).css({
                'left':'0',
                'top':'0'
            });
            changer.find('li.photo-'+j).addClass('selected');
            changer.find('li.photo-'+i).removeClass('selected');
            this.current === this.bin.length -1 ? this.current = 0 : this.current = this.current+1;
        }
    });
    $(document).ready(function (){
        if (!window.location.hash.match(/#\/.+/)){
            var loc = window.location.pathname.toString();
            window.location.replace('/#'+loc);
        }

        var rsd = window.RSD = {}; 
        rsd.app = appControl.init();
        rsd.gal = galControl.init();
        rsd.bg = bgControl.init();
        

        window.bgColor = function (){
            rsd.bg.color.call(rsd.bg, colorkey);
        }
        window.detailView = function (){
            rsd.gal.detailView.call(rsd.gal);
        }
        window.listToGrid = function (){
            rsd.gal.listToGrid.call(rsd.gal);
        }

    });
    window.resizeBackground = function(){
        // This fires on window.resize and when new content fades in
            var h = (wh = $(window).height(), dh = $(document).height(), wh > dh) ? wh : dh,
                w = (ww = $(window).width(), dw = $(document).width(), ww > dw) ? ww : dw;
        $('#grid').css({'height':h,'width':w})
    }
    $(window).resize(function(){
        window.resizeBackground();
    });
    $(window).load(function (){
        
        window.RSD.navcheck = function (){
            if (!window.location.hash.match(/#\/$/)) {
                 var hash = window.location.hash.slice(1),
                 link = $('a[href$='+hash+']');
                 if (link.hasClass('subnav')) {
                     link.addClass('subnavselected').closest('ul.subnav-ul').slideDown('slow').siblings('a').addClass('selected');
                 } else if (link.hasClass('nav')) {
                     link.addClass('selected').siblings('ul.subnav-ul').slideDown('slow');
                 }
                 if (link.parents().is('#nav-our-work')) {
                     window.RSD.app.ourwork.growline.call(this)
                 }
             }
        }
        window.RSD.navcheck();
        $('#for-mailing').live('click', function (){
            $(this).toggleClass('checked');
        });
        
        $('#map-container').live('click',function (){
            $('#gmap').toggle();
        });
        
        $('.print a').live('click', function (e){
            e.preventDefault();
            window.print();
        });
        
        $('form#subscribe').live('submit', function(e){
            this.errors = [];
            if ($('#id_name').val() === '') {
                this.errors.push([$('#id_name'), 'Name is required.'])
            }
            if (!/^([a-zA-Z0-9_.-])+@(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$/.test($('#id_emails').val())) {
                this.errors.push([$('#id_emails'), 'Valid email is required.'])
            }
            if (this.errors.length > 0) {
                _.each(this.errors, function(e){
                    e[0].addClass('error').val(e[1])
            });
            $('form#subscribe input.error').focus(function(){
                $(this).val('').removeClass('error');
            });
                return false;
            }
        })
        
        $('#contact-form').live('submit', function(e){
            this.errors = [];
            
            if ($('#id_name').val() === '') {
                this.errors.push([$('#id_name'), 'Name is required.'])
            }
            if (!/^([a-zA-Z0-9_.-])+@(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$/.test($('#id_email').val())) {
                this.errors.push([$('#id_email'), 'Valid email is required.'])
            }
            if ($('#id_comments').val() === '') {
                this.errors.push([$('#id_comments'), 'A message is required.'])
            }
            if (this.errors.length > 0) {
                _.each(this.errors, function(e){
                    e[0].addClass('error').val(e[1])
            });
            $('#contact-form input.error, #contact-form textarea.error').focus(function(){
                $(this).val('').removeClass('error');
            });
                return false;
            }
        })
        

});
})(jQuery);
window.bgColor = function(){return;} // This line prevents errors from being thrown on initial page launch.
window.ie = ($.browser.msie)
