//DS Global Object
 if (typeof DS == "undefined" || !DS) {
    var DS = {};
}

DS.menu = {
    state:null,
    init:function(){
        $(".scrollTo").click(function(event){
            event.preventDefault();
                                
            var full_url = this.href;
            var parts = full_url.split("#");
            var trgt = parts[1];
            var target_offset = $("#"+trgt).offset();
            var target_top = target_offset.top;
            $('html, body').animate({scrollTop:target_top}, 500);
        });        
        
        $(".lab").mouseenter(function(){
            if(DS.menu.state != 'lab'){ 
                $("#nav_lab_off").fadeOut(300);
                $("#nav_lab_on").fadeIn(300);                    
            }
            $("#nav_lab_circle").fadeIn(300); 
        }).mouseleave(function(){
            if(DS.menu.state != 'lab'){
                $("#nav_lab_off").fadeIn(300);
                $("#nav_lab_on").fadeOut(300);
            }
            $("#nav_lab_circle").fadeOut(300);  
        }).click(function(event){
            if(DS.menu.state != 'lab'){
                if(DS.slidePanel.isOpen){
                    DS.slidePanel.close();
                }                 
                DS.menu.state = 'lab';    
            } 
        });

        $(".gallery").mouseenter(function(){
             if(DS.menu.state != 'gallery'){
                $("#nav_gallery_off").fadeOut(300);
                $("#nav_gallery_on").fadeIn(300);
             }    
             $("#nav_gallery_circle").fadeIn(300);              
        }).mouseleave(function(){
             if(DS.menu.state != 'gallery'){            
                $("#nav_gallery_off").fadeIn(300);
                $("#nav_gallery_on").fadeOut(300);
             }  
             $("#nav_gallery_circle").fadeOut(300);              
        }).click(function(event){
            if(DS.menu.state != 'gallery'){
                if(DS.slidePanel.isOpen){
                    DS.slidePanel.close();
                }                
                DS.menu.state = 'gallery';
            }
        });
        
        $(".people").mouseenter(function(){
             if(DS.menu.state != 'people'){            
                $("#nav_people_off").fadeOut(300);
                $("#nav_people_on").fadeIn(300);
             }
             $("#nav_people_circle").fadeIn(300);                   
        }).mouseleave(function(){
             if(DS.menu.state != 'people'){            
                $("#nav_people_off").fadeIn(300);
                $("#nav_people_on").fadeOut(300);
             }  
             $("#nav_people_circle").fadeOut(300);              
        }).click(function(event){
            if(DS.menu.state != 'people'){
                if(DS.slidePanel.isOpen){
                    DS.slidePanel.close();
                }                 
                DS.menu.state = 'people';
            }
        }); 
        
        $(".myds").mouseenter(function(){
             if(DS.menu.state != 'myds'){            
                $("#nav_myds_off").fadeOut(300);
                $("#nav_myds_on").fadeIn(300);  
             }  
             $("#nav_myds_circle").fadeIn(300);             
        }).mouseleave(function(){
             if(DS.menu.state != 'myds'){            
                $("#nav_myds_off").fadeIn(300);
                $("#nav_myds_on").fadeOut(300);
             }  
             $("#nav_myds_circle").fadeOut(300);             
        }).click(function(event){
            if(!DS.menu.state != 'myds'){
                if(DS.slidePanel.isOpen){
                    DS.slidePanel.close();
                }             
                DS.menu.state = 'myds';
            }            
        });                    
    },
    fadeOut:function(id){
        if(id != null){
            $("#nav_" + id + "_off").fadeIn(300);
            $("#nav_" + id + "_on").fadeOut(300);
            $("#nav_" + id + "_circle").fadeOut(300);             
        }
    },
    fadeIn:function(id){
        if(id != null){
            $("#nav_" + id + "_off").fadeOut(300);
            $("#nav_" + id + "_on").fadeIn(300);
            //$("#nav_" + id + "_circle").fadeIn(300);             
        }
    },
    menuScroll:function(){
        if(!DS.slidePanel.isOpen){
            var posy = $(window).scrollTop();
            
            if(posy >= ($('#gallery').offset().top - 160) && posy < ($('#lab').offset().top - 160)){
                //lab
                DS.menu.state = "gallery";
                DS.menu.fadeIn("gallery");
                DS.menu.fadeOut("lab");
                DS.menu.fadeOut("people");
                DS.menu.fadeOut("myds");                                 
            }
            else if(posy >= ($('#lab').offset().top - 160) && posy < ($('#people').offset().top - 160)){
                //gallery
                DS.menu.state = "lab";
                DS.menu.fadeIn("lab");
                DS.menu.fadeOut("gallery");
                DS.menu.fadeOut("people");
                DS.menu.fadeOut("myds");                 
            }
            else if(posy >= ($('#people').offset().top - 160) && posy < ($('#people').offset().top + 400)) { 
                //people
                DS.menu.state = "people";
                DS.menu.fadeIn("people");
                DS.menu.fadeOut("lab");
                DS.menu.fadeOut("gallery");
                DS.menu.fadeOut("myds");                 
            }
            else if(posy >= ($('#people').offset().top + 400)) { 
                //myds
                DS.menu.state = "myds";
                DS.menu.fadeIn("myds");
                DS.menu.fadeOut("people");
                DS.menu.fadeOut("lab");
                DS.menu.fadeOut("gallery");                                
            }
            else{
                //null
                DS.menu.state = null;
                DS.menu.fadeOut("lab");
                DS.menu.fadeOut("gallery");
                DS.menu.fadeOut("people");
                DS.menu.fadeOut("myds");                
            }
            
                       
        }   
    }        
}

DS.util = {
    hasConsole:false,
    writeLog:false,
    init:function(){
        if (window.console) {
            this.hasConsole = true;
        }
        $("a.hoverable").mouseover(function() {
            $(this).fadeTo(100, 0.5);
        });
        $("a.hoverable").mouseout(function() {
            $(this).fadeTo(100, 1);
        });       
    },
    log:function(msg){
        if(this.writeLog == true){
            if(this.hasConsole == true){
                window.console.log(msg);
            }
            else{
                alert(msg);
            }        
        }
    },
    rand:function(){
        return Math.floor(Math.random()*100000);
    }
}

DS.ie = {
     fixedPositionSupport:function(){
        $(window).scroll(function() {
            $('#navigation').css('top', $(this).scrollTop() + "px");
            $('#slidePanelCloseContainer').css('top', $(this).scrollTop() + "px");
        });       
     },
     pngSupport:function(){
        $(document).pngFix();        
     }
};

DS.slidePanel = {
    pageY:0,
    isOpen:false,
    init:function(){
        $("#slidePanel").css("height",  $(document).height() );
        $(".slidePanelBtn").click(function(event){
            event.preventDefault();
            DS.slidePanel.open(this.href);
        });
        $("#slidePanelCloseBtn").click(function(event){
            event.preventDefault();
            DS.slidePanel.close();
        }); 
    },
    open:function(contentPage){
            DS.util.log(contentPage);      
            $("#slidePanel").animate({ left: "0px" }, '300')
            $("#slidePanelCloseContainer").animate({ left: "700px", top: "20px" }, '300');

            DS.slidePanel.isOpen = true;
            
            DS.slidePanel.pageY = $(window).scrollTop();      
            $("#slidePanelContent").css("top", (DS.slidePanel.pageY + 20)+"px");

            $("#slidePanelContent").load(contentPage+"?rand="+DS.util.rand()); // send random number as GET variable to prevent IE caching
            
            DS.slidePanel.scrolling.disable(); // disable page scrolling while slide panel is open
    },
    close:function(){      
            $("#slidePanel").animate({ left: "-760px" }, '300', function() {$("#slidePanelContent").html("<img src=\"img/ajax-loader.gif\"/>");})
            $("#slidePanelCloseContainer").animate({ left: "-40px" }, '300'); 
            DS.slidePanel.isOpen = false;  
            DS.slidePanel.scrolling.enable(); // restore page scrolling
    },
    scrollHandler:{
        x:'undefined',
        y:'undefined',
        onscroll:function(e){              
            if (DS.slidePanel.isOpen == 1 ){
                var  YOffset;
                if(document.all){
                     YOffset = (document.documentElement.scrollTop) ? document.documentElement.scrollTop : document.body.scrollTop;   
                }
                else{
                    YOffset = window.pageYOffset;    
                }
                
                if (DS.slidePanel.scrollHandler.x == 'undefined' )
                {
                    DS.slidePanel.scrollHandler.y = YOffset;
                }
                         
                diffY = DS.slidePanel.scrollHandler.y - YOffset;
                
                if( diffY > 0) 
                {
                    if ( DS.slidePanel.isOpen == 1 )               
                    {
                        if ( YOffset < DS.slidePanel.pageY ) 
                        {                        
                            $('html, body').animate({opacity: 1}, 500).animate({scrollTop:DS.slidePanel.pageY}, 300);
                        }
                        else 
                        {
                            $('html, body').stop();
                        }                    
                    }
                }
            }
                    
            DS.slidePanel.scrollHandler.x = window.pageXOffset;
            DS.slidePanel.scrollHandler.y = YOffset;            
        }
    },
    scrolling: {
        disable:function() {
            $("body").css("overflow", "hidden");
        },
        enable:function() {
            $("body").css("overflow", "");
        }
    }   
}

DS.carousel = {
    init:function(){
        // Create jCarouselLite object
        $(".carousel").jCarouselLite({
           btnNext: "a.carousel_next",
           btnPrev: "a.carousel_prev",
           circular: false,
           visible: 4
        });

        // Header Slideshow Carousel
        var home_slideshow = $("#home_slideshow").jCarouselLite({
           btnNext: "#home_slideshow_forward",
           btnPrev: "#home_slideshow_rewind",
           btnStartStop: "#home_slideshow_play_stop",
           clsStart: "home_slideshow_play",
           clsStop: "home_slideshow_stop",
           circular: true,
           auto:8000,
           visible: 1
        });    
    }
}

DS.photoGallery = {
    init:function(){
        $("a.photos").click(function(event) {
            event.preventDefault();
            $("#home_photos .fullsize img").attr("src", $(this).attr("href"));
        });      
    }
}

DS.portfolioHome = {
    init:function() {
        DS.portfolioHome.fancybox();
    },
    fancybox:function() {
        $("div#home_gallery a.fancybox").fancybox();
    }
}

DS.portfolio = {
    init:function() {
        $("a.panel").click(function(event) {
            event.preventDefault();
            
            var regexPageNum = /page:[0-9]*/;
			var pageNum = new String(this.href.match(regexPageNum));  		
			pageNum = pageNum.substr(pageNum.indexOf(":")+1, pageNum.length);

            $("#gallery_search").attr('action', '/portfolios/ajax_filter/page:'+pageNum);
            DS.portfolio.search();
        });
        
        // Setup appreciate + bookmark buttons
        DS.appreciate_btn.init();
        DS.bookmark_btn.init();
        
        // Initialize menu
        DS.portfolio.nav.init();
        
        // Gallery Fancybox
        DS.portfolio.fancybox();
		
		// Bind click event to search buttons
		$("a.button").bind("click", function() {
            var myName = $(this).attr("name");
            
            // Toggle the checkbox
            $("input.checkbox_"+myName).attr('checked', !($("input.checkbox_"+myName).attr('checked')));
            
            // Toggle the selected class
            $(this).toggleClass('selected');
            
            // Hide the gallery content and display the loading div
            $("#gallery_content").hide();
            $("#gallery_loading").show();
            
            // Disable the search buttons (the click event will be re-bound in the ajax response)
            $("a.button").unbind('click');

            // Submit the form
            $("#gallery_search").submit();
		});

    },
    nav: {
        init: function() {
            DS.portfolio.nav.fancybox();
        },
        fancybox: function() {
            $("#gallery_nav a.fancybox").fancybox({
                'overlayColor': '#000000',
                'overlayOpacity': 0.8
            });
        }
    },
    refresh:function() {

        // Reset the proper click event
        $("a.panel").click(function(event) {
            event.preventDefault();
            
            var regexPageNum = /page:[0-9]*/;
			var pageNum = new String(this.href.match(regexPageNum));  		
			pageNum = pageNum.substr(pageNum.indexOf(":")+1, pageNum.length);
			
            $("#gallery_search").attr('action', '/portfolios/ajax_filter/page:'+pageNum);
            $("#gallery_search").submit();
        });
        
        // Setup appreciate + bookmark buttons
        DS.appreciate_btn.init();
        DS.bookmark_btn.init();
        
        // Fancybox
        DS.portfolio.fancybox();
        
        // Hide the loading div, show the gallery div
        $("#gallery_loading").hide();
        $("#gallery_content").show();
        
        // Re-bind the click event to panel buttons
        // Bind click event to search buttons
		$("a.button").bind("click", function() {
            var myName = $(this).attr("name");
           
            // Toggle the checkbox
            $("input.checkbox_"+myName).attr('checked', !($("input.checkbox_"+myName).attr('checked')));
            
            // Toggle the selected class
            $(this).toggleClass('selected');
            
            // Hide the gallery content and display the loading div
            $("#gallery_content").hide();
            $("#gallery_loading").show();
            
            // Disable the search buttons (the click event will be re-bound in the ajax response)
            $("a.button").unbind('click');

            // Submit the form
            $("#gallery_search").submit();
		});
    },
    fancybox:function() {
        $("div#gallery_content a.fancybox").fancybox({
            'frameHeight': 504,
            'frameWidth': 853,
            'hideOnContentClick': false,
            'hideOnOverlayClick': true,
            'overlayColor': '#000000',
            'overlayOpacity': 0.8
        });
        /*
        $("div#gallery_content a.fancybox").mouseover(function() {
            $(this).fadeTo(100, 0.5);
        });
        $("div#gallery_content a.fancybox").mouseout(function() {
            $(this).fadeTo(100, 1);
        });
        */
    },
    search:function() {
        $("#gallery_search").submit(); // Submit ajax form!
    }
}

DS.appreciate_btn = {
    init: function() {
        $("a.appreciate_btn").click(function(event) {
            event.preventDefault();
            if(!($(this).hasClass("selected"))) {
                var this_id = $(this).attr('class').match(/[0-9]+/);
                DS.appreciate_btn.increment_each(this_id); // increment the counter of ALL visible appreciate buttons                
                $.ajax({url: $(this).attr('href')+'?rand='+DS.util.rand()}); // send the ajax request
            }
        });
    },
    increment_each: function(id) {
        $("a.appreciate_btn."+id).each(function() {
            $(this).children("span.count").text(Number($(this).children("span.count").text())+1); // increment the appreciate count
            $(this).addClass("selected");
        });
    }
}

DS.bookmark_btn = {
    init: function() {
		$("a.bookmark_btn").unbind('click');
        $("a.bookmark_btn").bind('click', function(event) {
			event.preventDefault();
            bookmark = $(this).parent();
            bookmark_id = bookmark.attr('class').match(/[0-9]+/);
			DS.bookmark_btn.toggle_each(bookmark_id); // toggle the selected state of ALL visible bookmark buttons
            
            $.ajax({url: $(this).attr('href')+'?rand='+DS.util.rand()}); // send the ajax request to the controller
            
            
            // Now add the newly bookmarked item to the homepage list
            if($(this).hasClass("selected")) {
                DS.favourites.description.hide();
                DS.favourites.add(bookmark); 
            }
            // Or, if we are unbookmarking an item, remove it from the homepage list
            else { 
                DS.favourites.remove(bookmark);
            }
                       
        });
    },
    toggle_each: function(id) {
		/*$("a.bookmark_btn."+id).each(function() {
            alert($(this).parent().html());
			$(this).toggleClass("selected");
        });*/
		$("a.bookmark_btn").each(function() {
            if($(this).hasClass(id)) {
				$(this).toggleClass("selected");
			}
        });
    }    
}

DS.remove_btn = {
    init:function() {
        $("a.remove_btn").click(function(event) {
            event.preventDefault();
            bookmark = $(this).parent();
            bookmark_id = bookmark.attr('class').match(/[0-9]+/);
            DS.bookmark_btn.toggle_each(bookmark_id); // toggle the selected state of ALL visible bookmark buttons
            
            $.ajax({url: $(this).attr('href')+'?rand='+DS.util.rand()}); // send the ajax request to the controller
            
            DS.favourites.remove(bookmark);
        });
    }
}    

DS.favourites = {
    init:function() {
        // Setup appreciate + bookmark buttons
        DS.appreciate_btn.init();
        DS.bookmark_btn.init();
        DS.remove_btn.init();
        
        DS.favourites.fancybox();         
        
        // If the favourites list contains at least one item, hide the description
        if($("ul#home_favourites").children().length > 0) {
            $("div#home_myds div.content div.description").hide();
        }
    },
    fancybox: function() {
        if($("ul#home_favourites").children().length > 0) {
            $("ul#home_favourites a.favourite").fancybox({
                'frameHeight': 480,
                'frameWidth': 853,
                'hideOnContentClick': false,
                'hideOnOverlayClick': true,                
                'overlayColor': '#000000',
                'overlayOpacity': 0.8
            });
        }
    },
    add: function(bookmark) {

        bookmark = bookmark.clone();
        bookmark_id = bookmark.attr('class').match(/[0-9]+/);       
        bookmark.addClass("favourite");
            
        // Hide all the fields/classes we don't want visible in the favourite window
        bookmark.find("a").removeClass("hidden");
        bookmark.find("a.appreciate_btn").remove();
        bookmark.find("a.bookmark_btn").addClass("remove_btn");
        bookmark.find("a.remove_btn").removeClass("bookmark_btn");
        bookmark.find("a.remove_btn").removeClass("selected");        
        bookmark.find("div.featuredtitle").remove();
        bookmark.find("a.fancybox").addClass("favourite");

        $("ul#home_favourites").append(bookmark);
        
        // Now reapply the fancybox methods
        DS.favourites.init();
    },
    remove: function(bookmark) {
        var bookmark_id = bookmark.attr('class').match(/[0-9]+/);
        $("ul#home_favourites li."+bookmark_id).remove();
        
        // Check if there are any bookmarks left
        if($("ul#home_favourites").children().length == 0) {
            DS.favourites.description.show(); // if not, display the bookmark helper image
        }
        else {
            DS.favourites.fancybox(); // if so, reapply the fancybox methods
        }
    },
    description: {
        hide: function() {
            $("div#home_myds div.content div.description").hide();
        },
        show: function() {
            $("div#home_myds div.content div.description").show();
        }
    }    
}


//jQuery Ready
$(document).ready(function(){
    if ($.browser.msie && $.browser.version == 6){
        DS.ie.fixedPositionSupport();
        DS.ie.pngSupport();
    }
    
    //DS.slidePanel.init();
    DS.util.init();
    
    //Toggle logging on and off globally here.
    DS.util.writeLog = false;
    
    //Some stuff is going to have to wait till window load
    $(window).load(DS.slidePanel.init);
    
    //Stick an event on the scrolling but only in non IE
    if (!$.browser.msie){
        window.onscroll = DS.slidePanel.scrollHandler.onscroll;    
    }
    
    //Setup carousels
    DS.carousel.init();
    
    //Setup portfolio home
    DS.portfolioHome.init();
    
    //Setup photo gallery
    DS.photoGallery.init();
    
    //Setup My Designstor bookmarks
    DS.favourites.init();
	 
	//Setup menu and attach scroll event handler     
    DS.menu.init();
    
    if (($.browser.msie && $.browser.version == 7) == false){
        DS.menu.menuScroll();
        $(window).scroll(DS.menu.menuScroll);
    }    
});







