    
    var $j = jQuery.noConflict();
    
    // Global Constants
    
    /* Overlays ----------------------------------------------------------------
    --------------------------------------------------------------------------*/
    var SHOW_OVERLAY = 10;
    var HIDE_OVERLAY = 11;
    var OVERLAY_VISIBLE = false;
    var OVERLAY_INACTIVE_COLOR = '';
    var OVERLAY_ACTIVE_COLOR   = '#aaa';
    
    
    /* Contact ----------------------------------------------------------------
    --------------------------------------------------------------------------*/
	var BASE_URL      = 'http://shootuk.com/';
	var MSG_ERROR     = 0;
	var MSG_SUCCESS   = 1;
	var MSG_SENDING   = 2;
	var NO_DELAY      = 0;
	var TIMEOUT       = 33;
	var msg_box_state = 0;
	var contact = {};
    
    var workApi = {};
    
    
    function videoOverlay(action, type, jq)
    {
        if (action == SHOW_OVERLAY) {
            
            if (OVERLAY_VISIBLE) {
                $j('.video-overlay').fadeOut('normal');
                OVERLAY_VISIBLE = false;
            }
            
            jq.parent().parent().parent().parent().find(type).fadeIn('normal');
            OVERLAY_VISIBLE = type;
            
        } else {
            $j('.video-overlay').fadeOut('normal');
            OVERLAY_VISIBLE = false;
        }
    }
    
    
    function displayMessage(msg, type, delay)
    {
        if (type == MSG_ERROR) {  
           display_class = 'msg-box-red'; 
        }
        
        if (type == MSG_SENDING) {
            display_class = 'msg-box-yellow';
        }
        
        if (type == MSG_SUCCESS) {
            display_class = 'msg-box-green';
        }
        
        if (msg_box_state === 0) {
            $j('#message-box').addClass(display_class).html(msg).fadeIn('slow');
            msg_box_state = 1;
        } else {
            // FADE OUT MSG BOX TEXT FIRST
            $j('#message-box').fadeOut('normal', function() {
                $j(this).removeClass().addClass(display_class).html(msg);
            });
            
            $j('#message-box').fadeIn('normal');
            
            msg_box_state = 1;
        }
        
        // FADEOUT DELAY
        // special case for sending message fade. requires a timeout.
        
        if (delay == NO_DELAY) {
            return;
        }
        
        if (delay == TIMEOUT) {
            $j('#message-box').animate({opacity: 1});
            setTimeout(function() {
                $j('#message-box').fadeOut('slow');
            }, 1500);
            // else if other type of delay
        } else if (delay) {
             $j('#message-box').animate({opacity: 1}, delay).fadeOut('slow');
        }
    }
    
    
    function validateContact()
    {
        var email_regex = /^([0-9a-zA-Z]([\-.\w]*[0-9a-zA-Z])*@([0-9a-zA-Z][\-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,9})$/;
        var msg = '';
        
        contact = {
            name:     jQuery.trim($j('#contact-name').val()),
            email:    jQuery.trim($j('#contact-email').val()),
            showreel: jQuery.trim($j('input.contact-radio:checked').val()),
            company:  jQuery.trim($j('#contact-company').val()),
            phone:    jQuery.trim($j('#contact-phone').val()),
            address:  jQuery.trim($j('#contact-address').val())
            };
            
        // Only validate the following..      
        if (!email_regex.test(contact.email)) {
            msg += '<li><b>Email</b> address not valid</li>';
        }
        
        if (contact.name === '') {
            msg += '<li>Please enter a <b>name</b></li>';
        }
        
        if (contact.showreel === '') {
            msg += '<li>Please choose a <b>showreel</b></li>';
        }
        
        if (contact.address === '') {
            msg += '<li>Please enter an <b>address</b></li>';
        }
        
        if (msg !== '') {
            displayMessage('<p>Please correct the following errors:</p><ul>'+msg+'</ul>', MSG_ERROR, NO_DELAY);
            return false;
        }
    
        return true;
    }
    
    
    function contactResultHandler(json_result)
    {
        if (json_result.code == 1) {
            displayMessage(json_result.result, MSG_SUCCESS, NO_DELAY);
        }
    }
    
    
    
    function buildPostStr()
    {
        var post_str = '';
        
        for (var field in contact) {
            post_str += field+'='+contact[field]+'&';
        }
        
        return post_str;
    }
    
    
    
    function submitContactForm()
    {
        displayMessage("<p>sending message..</p>", MSG_SENDING, NO_DELAY);
    
        // We set a timeout so that the 'sending message' dialog stays up a bit before 
        // the next message is shown
        setTimeout(function() {
            $j.ajax({
                url: BASE_URL + 'contact',
                type: "POST",
                data: buildPostStr(),
                success: 
                    function(response, status) {
                        contactResultHandler(response);
                    },
                error:
                    function(XMLHttpRequest, textStatus, errorThrown) {
                        displayMessage('<p>connection failed. please try again.</p>', MSG_ERROR, NO_DELAY);
                    },
                async: false,
                dataType: "json"
            });
        }, 1000);
    }
    
    
   
    function getLatestPosts()
    {
        // RSS feed parser
        $j.get(BASE_URL+'blog/feed/rss', function(result) {
            //
            var MAX = 3;
            var i   = 0;
            
            $$ = $j(result).find('item');
            $$.each(function() {
                //
                $j('#blog-news li').eq(i).find('a').attr('href', $j(this).find('link').text()).html($j(this).find('title').text());
                i++;
            });
        });
    }
    
    
    function slideSwitch()
    {
        var img_data = [];
        
        var $active = $j('#home-slideshow img.active');

        if ( $active.length === 0 ) {
            $active = $j('#home-slideshow img:last');
        }

        var $next =  $active.next().length ? $active.next() : $j('#home-slideshow img:first');

        $active.addClass('last-active');
        
        // get actives rel data    
        img_data = $next.attr('rel').split('.');
        
        $j('#home-slider-title').html(img_data[0]).attr({href: img_data[2]});
        $j('#home-slider-info') .html(img_data[1]).attr({href: img_data[2]});
        
        $next.css({opacity: 0.0})
            .addClass('active')
            .animate({opacity: 1.0}, 1000, function() {
                $active.removeClass('active last-active');
            });
    }
    
    
    // May no longer be needed
    function showGalleries(filter)
    {
        if (filter !== 'all') {
            filter = '> .cat-'+filter;
        } else {
            filter = ' .gallery-container';
        }
        
        $j('#vertical-slide > #pages '+filter).fadeIn('normal');
    }
    
    
    function ucwords(str){return(str+'').replace(/^(.)|\s(.)/g,function($1){return $1.toUpperCase();});}
    
    
    function initFlowplayer(theElement)
    {
        $f(theElement, BASE_URL+"flow/flowplayer.commercial-3.1.5.swf", {
                
            // configure both players to use rtmp plugin  
            clip: {  
                provider: 'rtmp',
                autoPlay: true
            },
            
            key: '#$efd2a3cc79147a5f42b',
             
            // here is our rtpm plugin configuration  
            plugins: {
            
                controls: null,
    
              rtmp: {   
                   // use latest RTMP plugin release 
                    url: BASE_URL+'flow/flowplayer.rtmp-3.1.3.swf',             
                    netConnectionUrl: 'rtmpt://e1f1.simplecdn.net/play'   
              }  
            }      
        });
    }


    $j(document).ready(function() {
        
        workApi = $j('.h-slider').scrollable({
           size: 1,
           vertical:false,
           loop:true,
           speed:500,
           nextPage: '.main-arrow-right',
           prevPage: '.main-arrow-left',
           api:true 
        });
        
        
        $j('.h-slider > .items > img').click(function() {
            //
            var lol     = $j(this).next().attr('src').split('/');
            var artist  = ucwords(lol[2].replace(/_/g, ' '));
            var project = ucwords(lol[3].replace(/_/g, ' '));
            
            var setText = $j('.info-left-photography');
            
            setText.find('.tbl-value-artist').html(artist);
            setText.find('.tbl-value-project').html(project);
            
        });
    
        
        // Main Sliders - directors and photographers
        $j('#vertical-slide').scrollable({
           size: 1,
           vertical:true,
           clickable:false,
           loop:true,
           speed:500,
           nextPage: '.vertical-next',
           prevPage: '.vertical-previous'
        });
        
        
        
        
        
        // Handle directors info overlays
        $j('.video-overlay-link').click(function() {
            
            $$ = $j(this);
            desired_overlay = $$.attr('rel');
            
            if (OVERLAY_VISIBLE != desired_overlay) {
                videoOverlay(SHOW_OVERLAY, desired_overlay, $$);
                $$.parent().find('a').css('color', OVERLAY_INACTIVE_COLOR);
                $$.css('color', OVERLAY_ACTIVE_COLOR);
            } else {
                videoOverlay(HIDE_OVERLAY, desired_overlay, false);
                $$.css('color', OVERLAY_INACTIVE_COLOR);
            }
    
           return false;
        });
        
        
        // Show and hide directors gallery arrows
        $j('.video-gallery-right').hover(function() {
            $j(this).find('.directors-arrows').fadeIn('normal').css('display','block');
        }, function() {
            $j(this).find('.directors-arrows').fadeOut('fast').css('display','block');
        });
        
        
        
        // Close overlay on 'x' click
        $j('.close-directors-overlay').click(function() {
            videoOverlay(HIDE_OVERLAY, false, false);
        });
        
        
        
        // Click Sorter
        $j('.sorter > span').click(function() {
            
            clicked = $j(this);
            cat_id  = $j(this).attr('id');

            if (cat_id == 'all') {
                $j('.gallery-container').fadeIn('normal');
            } else {
                $j('#vertical-slide > #pages > div:not(.cat-'+cat_id+')').fadeOut('normal', function() {
                    
                    elements = $j('#vertical-slide > #pages > .cat-'+cat_id);
                    
                    if (elements.length) {
                        elements.fadeIn('normal');
                    } else {
                        $j('#vertical-slide').before('<p>there seems to be nothing here</p>');
                    }
                });
            }
            
            $j('.sorter > span').removeClass('active-sort');            
            clicked.addClass('active-sort');
        });
                
        
            
        // Contact send
        $j('#contact-send').click(function() {
            //
            if (validateContact() === true) {	
                submitContactForm();
            }
            
            return false; 
        });
        
        
        // Set Video Controls
        // Have to set a timeout before init to allow safari enough time for
        // whatever.
        /*
        setTimeout(function() {
            $f("huluPlayer", "/swf/flowplayer-3.1.5.swf", { 
                // don't start automcatically 
                clip: { 
                    autoPlay: false, 
                    autoBuffering: true 
                }, 
                     
                // disable default controls 
                plugins: {controls: null} 
         
            // install HTML controls inside element whose id is "hulu" 
            }).controls("hulu", {duration: 25});         
        }, 10);
        */
        
        // Forgot Email slide
        $j('#forgot-email').toggle(
            function() {
                $j('#client-login').animate({
                    'height':'+=68px'
                });
            },
            function() {
                $j('#client-login').animate({
                    'height':'-=68px'
                });
            }
        );
        
        
        /* Submenu
        $j('.has-submenu').toggle(
            function() {
                $j(this).next('ul').slideDown('normal');
                return false;
            },
            function() {
                $j(this).next('ul').slideUp('normal');
                return false;
            }
        );
        */
        
        
        $j('.video-thumb').click(function() {
            //
            var section      = $j(this).parent().attr('class').split(' ').pop();
            var vid_path     = $j(this).attr('src');
            var directorName = vid_path.split('/', 3).pop().replace(/_/g, ' ');
        
            vid_path = 'mp4:shootukvideos/portfolio/'+vid_path.slice(10, -9)+'video.mp4';
            
            if (section === 'v-content') {
                var loadTo = 'a.v-rtmp';
            } else if (section === 'oc-content') {
                var loadTo = 'a.oc-rtmp';
            }

            $j(loadTo).attr('href', vid_path);
            
            initFlowplayer(loadTo);
              
            $j(this).parent().parent().parent().find('.video-director-name').html(directorName);
            
            return false;
        });
        
        /************************
         *
         * Photo section thumbnail seeker
         *
         *
         */
        $j('.photo-thumb').click(function() {
            //
            var pics_path   = $j(this).attr('src').split('/');
            var artistName  = pics_path[2].replace(/_/g, ' ');
            var projectName = pics_path[3].replace(/_/g, '-');
            var clnProjectName = pics_path[3].replace(/_/g, ' ');
            var projectClass = pics_path[3].replace(/_/g, '-');
            
            var cnt = 0;        
 
            $j('.h-slider > .items > img').each(function() {
                // 
                // go through and count each image. once we find the project we're looking for
                // we take the count as our index     
                var projectClass = $j(this).attr('class');

                if (projectName === projectClass) {
                    workApi.seekTo(cnt);
                    return false;
                }
                
                cnt++;
                
                var setText = $j('.info-left-photography');
            
                setText.find('.tbl-value-artist').html(ucwords(artistName));
                setText.find('.tbl-value-project').html(ucwords(clnProjectName));
            });
        });
        
        
        
        $j('#home-latest div:last').css('marginRight','1px');
        
        
        /*******
         * Client section
         *
         *
         */
        $j('#forgot-login').click(function() {
           $j('#forgot-form').show();
           $j('#login-form').hide();
           
           return false;
        });
        
        
        $j('#return-login').click(function() {
           $j('#forgot-form').hide();
           $j('#login-form').show();
           
           return false;
        });
        
        
        // Get original link color from css for the overlays
        OVERLAY_INACTIVE_COLOR = $j('.video-links > a').css('color');    
    });
