(function ($) {
	
	$.work = function (options) {
		return $.work.impl.init(options);
	};
	
	$.fn.work = function (options) {
		return $.work.impl.init(this, options);
	};
	
	/*
	 * work default options
	 */
	$.work.defaults = {
	    fileId:     null,
	    view:       'thumbnails'
	};
	
	$.work.impl = {
		
		/*
		 * work options
		 */
		opts: null,
		
		/*
		 * work helper
		 */
		helper: {},
		
		/*
		 * work grid
		 */
		grid: {},
		
		/*
		 * work caseStudy
		 */
		caseStudy: {},
		
		/*
		 * Initialize the work
		 */
		init: function (work, options) {
            
            var self = this;
            
            // suppress image loading
            $('div.work-container img').suppressLoad();
            
            self.opts = $.extend({}, $.work.defaults, options);
            
            // create the helper objects
            self.helper.main                = $('div.main-container');
            self.helper.loader              = $('div.loading-container');
            self.helper.scrollable          = $('div.scrollable');
            self.helper.cover               = $('<div class="scrollable-cover"></div>').insertAfter(self.helper.scrollable);
            self.helper.rotator             = self.helper.main.clone();
            self.helper.holder              = $('<div class="holder"></div>').css('height', self.helper.main.height() + 'px').insertAfter(self.helper.main);
            self.helper.blinder             = $('<div class="blinder"></div>').css('height', self.helper.main.height() + 'px').appendTo(self.helper.holder);
            
            self.grid.list                  = $(work);
            
            self.helper.staticNav = true;
            
            // init the grid
            if (self.opts.fileId == '')
            {
                self.initGrid();
            }
            else
            {
                self.showCaseStudy(self.opts.fileId);
            }
            
            // init the rotator
            self.helper.rotator
		        .addClass('rotator-container')
		        ;
		    self.helper.rotator.find('div.header, div.footer, img.background')
	            .remove()
	            ;
		    self.helper.rotator.find('div.scrollable-container')
	            .empty()
	            .append('<div class="scrollable-placer-full"><div class="scrollable"></div></div>')
		        ;
		    self.helper.rotator.find('div.content-container')
		        .css('height', self.helper.main.height() + 'px')
		        ;
		    
		    self.setFilter();
            
			return self;
		},
		
		/*
		 * Initialize the grid
		 */
		initGrid: function () {
			
			var self    = this;
			var sr = $.browser.msie ? "" : "sr";    //Exclude select replace from IE
			//var sr = "sr";
			
    		// create the grid objects
			self.grid.container         = self.grid.list.parent().css('display', 'block');
			self.grid.controlContainer  = $('<div class="workcontrol-container"></div>').prependTo(self.grid.container);
			self.grid.filterType        = $('<div class="filter filter-type"><select id="type" class="select-filter '+sr+'"></select></div>').appendTo(self.grid.controlContainer);
            self.grid.filterService     = $('<div class="filter filter-service"><select id="service" class="select-filter '+sr+'"></select></div>').appendTo(self.grid.controlContainer);
            //self.grid.filterButton      = $('<a id="filter-work" class="button" href="#" title="Go">Go</a>').appendTo(self.grid.controlContainer);
            self.grid.workViews         = $('<ul class="workview-collection button-container"></ul>').appendTo(self.grid.controlContainer);
		    
		    // build the filters
            self.grid.filterType.find('select')
                .append('<option value="0">Select Type</option>')
                .append('<option value="All">View All</option>')
                .append('<option value="Fashion">Fashion</option>')
                .append('<option value="Media and Entertainment">Media &amp; Entertainment</option>')
                .append('<option value="Travel and Real Estate">Travel &amp; Real Estate</option>')
                .append('<option value="Watch and Jewelry">Watch &amp; Jewelry</option>')
                .append('<option value="Multi-Brand Retail">Multi-Brand Retail</option>')
                .append('<option value="Home">Home</option>')
                .append('<option value="Wines and Spirits">Wines &amp; Spirits</option>')
                .append('<option value="Fragrance and Beauty">Fragrance &amp; Beauty</option>')
                ;
            self.grid.filterService.find('select')
                .append('<option value="0">Select Service</option>')
                .append('<option value="All">View All</option>')
                .append('<option value="Interactive">Interactive</option>')
                .append('<option value="Ecommerce">Ecommerce</option>')
                .append('<option value="Online Marketing">Online Marketing</option>')
                .append('<option value="Software">Software</option>')
                .append('<option value="Photography and Video">Photography &amp; Video</option>')
                ;
            
            // eplace the select boxes
            self.grid.controlContainer.find('select.sr').replaceSelect();
            
            // build the view switcher
            self.grid.workViews
                .append('<li><a class="button clients" href="#" title="Client">Clients</a></li>')
                .append('<li><a class="button thumbnails active" href="#" title="Thumbnails">Thumbnails</a></li>')
                ;
            
            // init the scroll pane
            self.helper.scrollable.jScrollPane({
                scrollbarWidth: 16,
                scrollbarMargin: 0,
                showArrows: 'true',
                wheelSpeed: 32
            });
            
            // loop through work items
            self.grid.list.children().each(function(i, item){
                
                var $title = $(item).find('.workitem-title').clone();
                
                $(item)
                    .append($title.clone().addClass('workview-clients-hover'))
                    .append($title.clone().addClass('workview-clients'))
                    .append($title.clone().addClass('workview-thumbnails'))
                    .append($title.clone().addClass('workview-cover').removeAttr('style'))
                    ;
                
                // *** NOTE ***  
                // Removed and added to Work.aspx
                /* // Append case study link
                if ($(item).find('div.workitem-casestudy').length > 0)
                {
                    $(item).find('ul.workitem-url-collection').prepend('<li><a class="open-casestudy" href="?casestudy=' + $(item).attr('id') + '" title="View Case Study">View Case Study</a></li>');
                }
                */
                
                // show the image
                $(new Image()).load(function(){
                    
                    $(item).find('.workview-cover').fadeTo(300, '0.00');
                    
                }).attr('src', $.data($(item).find('img.workitem-grid-image').get(0), 'src'));
                
            });
            
            // et the view
            self.setView(self.opts.view);
            
            // show the work
            self.helper.cover.fadeOut(500, function(){
                $(this).remove();
            });
            self.helper.loader.fadeOut(500);
            
            // bind the grid events
            self.bindGridEvents();
		    
		    return;
		},
		
		/*
		 * Bind the events
		 */
		bindGridEvents: function () {
		    
		    var self    = this;
            
            // project link click
            self.grid.list.find('a.open-casestudy').click(function(e){
            
                if(self.helper.staticNav)
                    return; 
                    
                e.preventDefault();
                self.showCaseStudy($(this).parent().parent().parent().attr('id'));
            });
		    
		    // view button click
		    self.grid.workViews.find('a').click(function(e){
                e.preventDefault();
                
                    if ($(this).hasClass('thumbnails'))
                    {
                        self.setView('thumbnails');
                    }
                    else
                    {
                        self.setView('clients');
                    }
                    self.grid.workViews.find('a.active').removeClass('active');
                    $(this).addClass('active');
            });
		    
		    return;
		},
		
		/*
		 * Set the events for filtering selction and processing
		 */
		setFilter: function() {
    		var typePrefix = "type-";
    		var servicePrefix = "service-";
    		
		    
    		function filterClientList(){
		        var typeFilter = $('#type').attr("value").replace(/\s/g,'');
		        var serviceFilter = $('#service').attr("value").replace(/\s/g,'');
                
		        //Hide container first
                $('.workitem-collection').fadeOut(function() {
                    //___Type Filter ___
                    if(typeFilter == "All" || typeFilter == "0") {
                        $('.workitem').show();
                    }
                    else {
                        //init all items to hidden
                        $('.workitem').hide();
                        //select items that contain this type
                        var typesToShow = $('ul.workitem-collection').find("li[class*='"+ typePrefix + typeFilter+"']");
                        typesToShow.show();
                    }
                    
                    //___Service Filter ___
                    if(serviceFilter == "All" || serviceFilter == "0") {
                        //inherit type filter
                    }
                    else {
                        //hide items that dont have this service
                        $(".workitem:not(." + servicePrefix + serviceFilter + ")").hide();
                    }
                        
                    //Bring container back into view
                    $('.workitem-collection').fadeIn("fast");
                });
                
                //Fix weird view type bug, so view will refresh on selector change
                if($.browser.msie) {
            		var inactiveViewType = $('ul.workview-collection a:not(.active)');
            		var activeViewType = $('ul.workview-collection a.active');
            		inactiveViewType.click();
            		activeViewType.click();
                }
            }
            
    		$('a.sr-option').click(filterClientList);   //For select replace
    		$('select.select-filter').change(filterClientList); //For select dropdown
		},
		
		/*
		 * Set the view
		 */
		setView: function (view) {
		    
		    var self    = this;
		    
		    if (self.grid.view == view)
		        return;
		    
		    self.grid.view = view;
		    
		    if (view == 'thumbnails')
		    {
		        self.grid.list
		            .addClass('thumbnails')
		            .removeClass('clients')
		            ;
		        
		        self.grid.list.children().each(function(i, item){
                    
                    $(item).find('.workview-thumbnails').fadeIn(300);
                    
                });
                
                self.grid.list.find('.workview-cover').css({
                    display:    'block'
                });
                
                self.grid.list.children().unbind().hover(
                    function(){
                        $(this).queue("fx", []);
                        $(this).find('.workview-cover').fadeTo(200, '0.50');
                        $(this).find('ul').fadeIn(200);
                    },
                    function(){
                        $(this).queue("fx", []);
                        $(this).find('.workview-cover').fadeTo(200, '0.00');
                        $(this).find('ul').fadeOut(200);
                    }
                );
		    }
		    else if (view == 'clients')
		    {
		        self.grid.list
		            .addClass('clients')
		            .removeClass('thumbnails')
		            ;
		        
		        self.grid.list.children().each(function(i, item){
		        
                    $(item).find('.workview-thumbnails').fadeOut(300);
                    
                });
                
                self.grid.list.find('.workview-cover').css({
                    display:    'none'
                });
                
                self.grid.list.children().unbind().hover(
                    function(){
                        $(this).queue("fx", []);
                        $(this).find('.workview-clients').fadeOut(200);
                        $(this).find('ul').fadeIn(200);
                    },
                    function(){
                        $(this).queue("fx", []);
                        $(this).children('.workview-clients').fadeIn(300);
                        $(this).find('ul').fadeOut(200);
                    }
                );
		    }
		    
		    return;
		},
		
		/*
		 * Initialize the case study
		 */
		initCaseStudy: function () {
		    
		    var self    = this;
		    var step    = self.helper.main.height();
		    var pwf     = self.data[self.index];
		    
		    // show the loader
		    self.helper.loader.fadeIn(500);
		    
		    // init blinder
		    self.helper.blinder.css({
	            top:    -step + 'px'
	        });
	        
	        // init holder
		    self.helper.holder.css({
		        display:    'block'
		    });
		    
		    // blind down
            self.helper.blinder.animate({top: 0}, 500, 'easeOutCubic', function(){
    		    
		        // get the background path
		        $.each(pwf['PublishedBaseFile']['BaseFileRelatedFiles'], function(i, item){
    		        
		            if (item['AttributeName'] == 'Background Image')
                    {
                        
	                    // load the background
                        $(new Image()).load(function(){
                            
                            self.helper.background
                                .css('display', 'block')
                                .empty()
                                .append($(this))
                                ;
                            
                            // size the background
                            self.resizeBackground(this);
                            
                            // hide the loader
                            self.helper.loader.fadeOut(500);
                            
                            // blind out
                            self.helper.blinder.animate({top: step + 'px'}, 500, 'easeOutCubic', function(){
            	                
            	                // append the project
            	                var r = self.helper.rotator.clone().insertAfter(self.helper.background);
            	                
            	                r.find('div.scrollable-container')
	                                .css({
	                                    opacity:    '0.00',
	                                    display:    'block'
	                                })
	                                ;
                                
                                r.find('div.scrollable').append(self.buildProject().container);
                                
                                r.find('div.scrollable')
                                    .jScrollPane({
                                        scrollbarWidth: 16,
                                        scrollbarMargin: 0,
                                        showArrows: 'true',
                                        wheelSpeed: 32
                                    })
                                    ;
                                
                                r.find('div.scrollable-container')
                                    .css({
                                        opacity:    '1.00',
                                        display:    'none'
                                    })
                                    ;
                                
                                r.find('div.scrollable-container')
                                    .fadeTo(500, '0.00', function(){
                                        $(this)
                                            .css('opacity', '1.00')
                                            .fadeIn(500)
                                            ;
                                    })
                                    ;
            	                
            	                // hide the holder
                                self.helper.holder
                                    .css({
                                        display:    'none'
                                    })
                                    ;
            	                
                            });
                            
                        }).attr('src', json.ctsServerUrl + '/uploadedfiles/' + item['SystemFileName']);
                        
                        return;
                    }
    		        
		        });
		        
		    });
		    
		    return;
		},
		
		/*
		 * Show the case study
		 */
		showCaseStudy: function (fileId) {
		    
		    var self    = this;
		    var step    = self.helper.main.height();
		    
		    // create the helper objects
		    self.caseStudy.container    = $('#' + fileId);
			
			// show the loader
		    self.helper.loader.fadeIn(500);
		    
		    // init blinder
		    self.helper.blinder.css({
	            top:    -step + 'px'
	        });
	        
	        // init holder
		    self.helper.holder.css({
		        display:    'block'
		    });
		    
		    // blind down
            self.helper.blinder.animate({top: 0}, 500, 'easeOutCubic', function(){
                
                // load the background
                $(new Image()).load(function(){
                    
                    self.caseStudy.background = $('div.background-container').clone()
                        .attr('class', 'casestudy-background')
                        .css('display', 'block')
                        .empty()
                        .append($(this))
                        .insertAfter(self.helper.main);
                        ;
                    
                    // size the background
                    self.resizeBackground(this);
                    
                    // hide the loader
                    self.helper.loader.fadeOut(500);
                    
                    // blind out
                    // NOTE: If the duration for this animate call is set to anything larger than 1
                    // NOTE: IE6 & IE7 end up making a call to the "attr" function in jquery core
                    // NOTE: attempting to set the "height" of some object to a negative number (-16px).
                    // NOTE: This request is deemed illegal in IE's DOM handling engine and throws a
                    // NOTE: javascript error that blows up the page. The problem was fixed by
                    // NOTE: modifying jquery core to weed out attempts to set height or width to negative
                    // NOTE: numbers., but its a bad idea to modify jquery core. So we use browser sniffing
                    // NOTE: to change the duration for IE only.
                    var iDurationForAnim = 500;
                    jQuery.each(jQuery.browser, function(i, val) {
                      if(i=="msie" && val==true) {
                         iDurationForAnim = 1;
                      }   
                    });
                    self.helper.blinder.animate({top: step + 'px'}, iDurationForAnim, 'easeOutCubic', function(){
    	                		    		    
    	                // append the project
    	                var r = self.helper.rotator.clone().insertAfter(self.caseStudy.background);
    	                
    	                r.find('div.scrollable-container')
                            .css({
                                opacity:    '0.00',
                                display:    'block'
                            })
                            ;
                        
                        r.find('div.scrollable').append(self.buildCaseStudy(fileId));

                        r.find('div.scrollable')
                            .jScrollPane({
                                scrollbarWidth: 16,
                                scrollbarMargin: 0,
                                showArrows: 'true',
                                wheelSpeed: 32,
                                reinitialiseOnImageLoad: false
                            })
                            ;
                                                    
                        r.find('div.scrollable-container')
                            .css({
                                opacity:    '1.00',
                                display:    'none'
                            })
                            ;
                        
                        r.find('div.scrollable-container')
                            .fadeTo(500, '0.00', function(){
                                $(this)
                                    .css('opacity', '1.00')
                                    .fadeIn(500)
                                    ;
                            })
                            ;
    	                
    	                // hide the holder
                        self.helper.holder
                            .css({
                                display:    'none'
                            })
                            ;
                               	                
                    });

                }).attr('src', $.data($('#' + fileId + ' img.workitem-background-image').get(0), 'src'));
    
		    });
		    
		    return;
		},
		
		/*
		 * Build the case study
		 */
		buildCaseStudy: function (fileId) {
		
		    var self = this;
            
		    var file        = self.grid.list.find('#' + fileId);
		    var cs          = $('<div class="article-container"><div class="page-controls"></div><div class="page-content"></div></div>');
		    
		    var launchLink = file.find('a.launchLink').attr("href");
		    
		    //Get siblings' ids
		    var prevFileId = file.prev().attr("id");
		    var nextFileId = file.next().attr("id");
		    
		    //Setup next/prev links
		    if(prevFileId) { var prevLink = "?casestudy=" + prevFileId; }
		    else { var prevLink = "#"; }
		    
		    if(nextFileId) { var nextLink = "?casestudy=" + nextFileId; }
		    else { var nextLink = "#"; }
		    
		    cs.find('.page-controls')
                .append('<ul class="button-container right"><li><a class="button launch-site-for-casestudy" href="' + launchLink + '" title="Launch Site" target="_blank">Launch Site</a></li><li><a class="button prev-casestudy" href="'+ prevLink +'" title="Previous">Prev</a></li><li><a class="button next-casestudy" href="' + nextLink +'" title="Next">Next</a></li></ul>')
		        .append('<ul class="button-container left"><li><a class="button close-casestudy" href="?" title="Back">Back</a></li></ul>')
                .append('<div class="clear"></div>')
                ;
            
            // bind the controls
            cs.find('a.close-casestudy').click(function(e){
                if(self.helper.staticNav)
                    return; 
                    
                e.preventDefault();
                
                self.closeCaseStudy();
                
            });
            
            //Previous link
            cs.find('a.next-casestudy').click(function(e){
                if(self.helper.staticNav)
                    return; 
                e.preventDefault();
                self.closeCaseStudy();
                
                self.showCaseStudy($(file).next().attr("id"));
            });
            
            //Next link
            cs.find('a.prev-casestudy').click(function(e){
                if(self.helper.staticNav)
                    return; 
                    
                e.preventDefault();
                self.closeCaseStudy();
                
                self.showCaseStudy($(file).prev().attr("id"));
            });

            // video 
            var flvPath = $('#video-'+fileId).attr("class");
            loadSwf('/swf/video_483x298.swf',flvPath,launchLink,'video-'+fileId);                
            
            // load necessary images
            file.find('.image-collection-casestudy-challenge li').each(function(){
                var sSrc = $.data($(this).find('img').get(0), 'src');
                $(this).remove();
                var oImg = $(new Image()).load(function(){
                    $('.image-collection-casestudy-challenge').css('display', 'block');
                }).attr('src', sSrc); 
                file.find('.image-collection-casestudy-challenge').append('<li>');
                file.find('.image-collection-casestudy-challenge li:last').append($(oImg));
                $.data($(oImg).get(0), 'src', $(oImg).attr('src'));
            });
            file.find('.image-collection-casestudy-solution li').each(function(){
                var sSrc = $.data($(this).find('img').get(0), 'src');
                $(this).remove();
                var link = $('<a href="' + launchLink + '" target="_blank">');
                var oImg = $(new Image()).load(function(){
                    $('.image-collection-casestudy-solution').css('display', 'block');
                }).attr('src', sSrc); 
                file.find('.image-collection-casestudy-solution').append('<li>');
                link.append(oImg);
                file.find('.image-collection-casestudy-solution li:last').append(link);
                $.data($(oImg).get(0), 'src', $(oImg).attr('src'));
            });
            file.find('.image-collection-casestudy-results li').each(function(){
                var sSrc = $.data($(this).find('img').get(0), 'src');                           
                $(this).remove();
                var link = $('<a href="' + launchLink + '" target="_blank">');
                var oImg = $(new Image()).load(function(){
                    $('.image-collection-casestudy-results').css('display', 'block');
                }).attr('src', sSrc);
                file.find('.image-collection-casestudy-results').append('<li>');                
                link.append(oImg);
                file.find('.image-collection-casestudy-results li:last').append(link);
                $.data($(oImg).get(0), 'src', $(oImg).attr('src'));
            });
                        
            // append the content
            cs.find('.page-content')
                .append('<h1>' + $(file.find('.workitem-title')[0]).text() + '</h1>')
                .append(file.find('.workitem-casestudy').clone().css('display', 'block'))
                ;
               
            // turn on slideshow effect for each image-collection in the case study
            cs.find('.image-collection').cycle({
                fx: 'fade', 
                speed: 1500
            });
			            
    	    return cs;
		},
		
		/*
		 * Close the case study
		 */
		closeCaseStudy: function () {
		    
		    var self    = this;
		    var step    = self.helper.main.height();
		    
		    // init blinder
		    self.helper.blinder.css({
	            top:    step + 'px'
	        });
	        
	        // init holder
		    self.helper.holder.css({
		        display:    'block'
		    });
		    
		    // blind up
            self.helper.blinder.animate({top: 0}, 500, 'easeOutCubic', function(){
    		    
                self.caseStudy.background
                    .css({
                        display:    'none'
                    })
                    .empty()
                    ;
                
                $('div.rotator-container').remove();
                
                // blind out
                self.helper.blinder.animate({top: -step + 'px'}, 500, 'easeOutCubic', function(){
	                
	                // hide the holder
                    self.helper.holder.css({
                        display:    'none'
                    });
	                
                });
		        
		    });
		    
		    return;
		},
		
		/*
		 * Resize the background image
		 */
		resizeBackground: function (img) {
		    
            if ($(window).width()/$(window).height() > $(img).width()/$(img).height())
            {
                $(img).css({
                    width:      '100%',
                    height:     $(img).height()/$(img).width()*$(window).width() + 'px',
                    display:    'block'
                });
            }
            else
            {
                $(img).css({
                    width:      $(img).width()/$(img).height()*$(window).height() + 'px',
                    height:     '100%',
                    display:    'block'
                });
            }
		    
		    return;
		}
		
	};
})(jQuery);