var Gallery = new gallery();

if (typeof console == "undefined" || typeof console.log == "undefined") var console = { log: function() {} };

function handleSection(elem, e, secondaryURL) {
    console.log('Call to handle section for elem: '+elem+' : '+secondaryURL);
    // Handles the opening or closing of a main page section such as pages
    // or portfolio bits - will need to call this before expanding showcase items
    // If secondaryURL is given then on success expanding it will call a load on
    // the portfolio bits. 

    // If we need to load the blog then do that first and drop out
    if($(elem).attr('href')=='#!/blog') {
        loadBlog();
        console.log('Loading blog');
        return true;
    }
    $('html,body').animate({ scrollTop: $(elem).offset().top }, { duration: 'slow', easing: 'swing'});
    // Handling for the pages/portfolio stuff
    if($(elem).attr('class') != 'active') {
        $('html,body').animate({ scrollTop: $(elem).offset().top }, { duration: 'slow', easing: 'swing'});
    }

    var block = $('.expand');
    $(elem).parent().parent().children('.expand').delay(800).slideToggle(400);
    $(elem).next().delay(800).slideToggle('slow');
    $(elem).children().css('opacity', '1');

    if($(elem).attr('href')=='#!/pages') {
        // If we are actually loading a page then just pass through the secondryURL
        console.log('We have a pages url');
        if((secondaryURL)=='/pages') {
            secondaryURL = '#!/pages/about-us/'; //hack! but bus is coming!
            window.location = secondaryURL;
        }
        console.log('Secondary is for pages: '+secondaryURL);
        loadPorfolioItem(secondaryURL);
    }

    if ($(elem).attr('class') != 'active' )     {
        var targetURL = convertAjaxUrl($(elem).attr('href'));
        var targetDIV = targetURL.replace(/\//g, ''); // turn into just name
        $(elem).toggleClass("active");
        $('#'+targetDIV+'_content').load(targetURL, function() {
                if(secondaryURL!=undefined) {
                    loadPorfolioItem(secondaryURL);
                }
            }
        );
    }
    else {
        $('.portfolio-nav').css({'opacity':'0', 'display':'none'});
        $(elem).toggleClass("active");
        if(e)
            e.preventDefault();
    }
}

function findTrigger(href) {
    // Finds the element on the page with a given href to call the section
    // expand function with (uses first one it finds)
    var trigger = false;
 
    var splitHref = href.split('/');
    if(splitHref.length>1) {
        // Do we have a url like /portfolio/3-way/? if so handle the first bit
        // to get the section we need to expand
        href = '/'+splitHref[1];
        console.log('Splitting URL up, looking for '+href);
    }
    $('ul#collapse').find('a').each(function () {
        if(convertAjaxUrl($(this).attr('href'))==href) {
            console.log('Got a match for incoming href: '+href);
            trigger = this;
            return false;
        }
    });
    return trigger;
}

function checkAndHandlePreload(inputURL) {
    // Takes an full url, eg http://u-dox.com/#!/portfolio/3-way/ and
    // handles loading the ajax content on page load
    var ajaxFragment = convertAjaxUrl(inputURL);
    if(ajaxFragment) {
        console.log('Initial fragment is '+ajaxFragment);
        var targetTrigger = findTrigger(ajaxFragment);
        if(targetTrigger) {
            console.log('Target trigger is : '+$(targetTrigger).attr('id'));
            handleSection(targetTrigger, undefined, ajaxFragment);
        } else {
            console.log('No trigger was found');
        }
        return true;
    } else {
        // Default action is to collapse all bits and then load in
        // the blog... we handle this by letting it return false
        console.log('We have no fragment, doing default and loading blog');
    }
    return false;
}

function loadBlog() {
    $('.expand:last').show().load('/blog/');
}

function convertAjaxUrl(ajaxURL) {
    // Take a url like /#!/porfolio/vans/ and return the bit *after* the #!
    var original = ajaxURL;
    ajaxURL = ajaxURL.split('#!');
    if(ajaxURL.length == 2) {
        // We have an ajax fragment
        console.log('Converted '+original+' to '+ajaxURL[1]);
        return ajaxURL[1];
    }
    return false;
}

function loadPorfolioItem(href, parentEl) {  
    if(href=='/portfolio' || href=='/spinetv')
        return false; // don't process the actual root page
    if ($.browser.msie) {
        servUrl = href.substr(0,href.indexOf('#!')-1);
        href = href.substr(href.indexOf('#!'), href.length)
    }
    //console.log('Loading in portfolio item '+href + 'servUrl: ' + servUrl); 
    var elementToLoad = href.replace('#!',''); 
    var elem = findTrigger(href);
    console.log('var elem: ' + elem);
    console.log('loadPorfolioItem trigger: '+$(elem).attr('id'));

    //ie adds site url to variable which ends with '/' so we have one extra
    //elementToLoad = elementToLoad.replace('/portfolio','portfolio');
    //elementToLoad = elementToLoad.replace('/pages','pages');
    var elementInDOM = $('.case_study');

    if ($(elem).attr('id')=='pages-trigger') {
        elementInDOM = $('#aboutUs_content');
    } else {
        $('.portfolio-trigger').css('opacity','1');
    }

    if (elementInDOM.html() == null)
        var elementInDOM = $(elem).parent('.section_content');

    if (elementInDOM.css('display') != 'block' && $(elem).parent().parent().attr('class') != 'item-navigation') {
        //Removed because we don't have time to do this properly
        $('.spinetv-nav').animate({'opacity':'1'}, 100);
        elementInDOM.slideToggle(400, function(){

        });
    } 
    if ($(elem).attr('id') != 'pages-trigger')
    {
        console.log('parentEl: ' +parentEl);
        if (parentEl != 'item-navigation'  ) {  
            // Here we handle getting the next/prev portfolio pieces based on the current active one
            var pieces = new Array();
            var count = 0;
            var currentIndex = 0; 
            $(elem).parent().next('div').find('ul.portfolio-list .item_detail').each(function () {
           
                // The urls here should be the NORMAL urls - not the #! bits so
                // the actual core bit of content is found and loaded, not the site   
                
                if(!$.browser.msie) {var pieceHref = $(this).attr('href').replace('#!', '');}
                else {var pieceHref = $(this).attr('href').replace('/#!', ''); var hrefIE = servUrl + href;}
                
                pieces.push(pieceHref);      
                if ($.browser.msie) {
                    if (pieceHref==hrefIE.replace('#!', '')) {
                        currentIndex = count;
                    }
                }
                else {
                    if (pieceHref==href.replace('#!', '')) {
                        currentIndex = count;
                    }
                }
                count++;
            });
            console.log('current index is '+currentIndex);
            var elementHref = pieces[currentIndex];
            console.log('current elementHref is : ' +elementHref);
            if(currentIndex-1>=0) {
                prevHref = pieces[currentIndex-1];
                console.log('set prev to '+prevHref);
            } else {
                prevHref = undefined;
            }
            if(currentIndex+1<=pieces.length) {
                nextHref = pieces[currentIndex+1];
                console.log('set next to '+nextHref);
            } else {
                nextHref = undefined;
            }
            console.log('set prevRef on portclick to '+prevHref);
            console.log(pieces);
            if (typeof prevHref === 'undefined') {
                $('.show-previous').css('visibility','hidden'); 
                $('.show-next').css('visibility','visible');
            }
            else if (typeof nextHref === 'undefined') {
                $('.show-next').css('visibility','hidden'); 
                $('.show-previous').css('visibility','visible');
            }
            else {
                $('.show-previous, .show-next').css('visibility','visible');
            }
            $('.show-previous').attr('href', prevHref);
            $('.show-next').attr('href', nextHref);
        }
    }

    elementInDOM.load(elementToLoad, function(){
        if (typeof prevHref === 'undefined') { $('.show-previous').css('visibility','hidden')}
        else if (typeof nextHref === 'undefined') {$('.show-next').css('visibility','hidden')}

         //console.log('PLI nextItem: ' + nextItem + ', prevItem: ' + prevItem);
    });
}
//Functions for sliding an element by it's own or target height

function slideDownByElemHeight(targetElem, heightElem) {
    if (heightElem == undefined){
        height = targetElem.height();
    } else {
        height = heightElem.height();
    }

    targetElem.animate({ 
        marginTop: '+='+height+'px'
        },500);
    }
                
function slideUpByElemHeight(targetElem, heightElem) {
    if (heightElem == undefined){
        height = targetElem.height();
    } else {
        height = heightElem.height();
    }

    targetElem.animate({ 
        marginTop: '-='+height+'px' 
        },500);
    }

$(document).ready(function(){
// expand site by url on load
    var browserUrl = window.location.toString();
    var hadPreload = checkAndHandlePreload(browserUrl);
    if(browserUrl.indexOf("?email-sent") != -1)
    $('.request_info').slideToggle(600).delay(4000).slideToggle(400);
    $('.expand').hide();
    $('.expand:first').show();
    if(!hadPreload) {
        loadBlog();
    }
    
    $('.portfolio-list .item_detail, .bigPicture li .overlay').live('click',function(){
        if(($(this).parent().parent().attr('class') == 'bigPicture' && $(this).parent().attr('class') != 'pic1b') || $(this).attr('class') != 'active') {
            $('html,body').animate({ scrollTop: $('#portfolio-trigger').offset().top }, { duration: 'slow', easing: 'swing'});
        }
    });


// VALIDATE CONTACT FORM ETC
    var objRegExp  = /^(\w+[\-\.])*\w+@(\w+\.)+[A-Za-z]+$/;                              
    $('#error-msg').hide();
    $(".submitMe").click(function() {
        $('.request_info').hide();
        
        var name = $("input#name").val();
        var email = $("input#email").val();
        var message = $("textarea#message").val();
        
        if (name == "" || email == "") {
            $("#error-msg").show().delay(4000).hide();
            return false;
        }
        var dataString = 'name='+ name + '&email=' + email + '&message=' + message;
        if (!objRegExp.test(email)) return false;
        //alert (dataString);return false;
        $.ajax({
            beforeSend: function(email) {
                if (name == "Name" || email == "Email" || name == "" || email == "") {
                    return false;
                }    
                
            },
            type: "POST",
            url: "/send-email/",
            data: dataString,
            success: function() {
                $('.request_info').show().children('h1').empty().append('Thank You!');
                $('.request_info').removeClass('bad').addClass('good').show().children('p').empty().append('Thank you for your getting in touch. We will be get back to you soon.');        
                //$('.submitMe').attr("disabled", true);
            }
        });
        return false;
    });
 
    jQuery("#contact-us, #commentform").validationEngine({
        scroll: false,
        ajaxSubmit: true,
        ajaxSubmitFile: "",
        ajaxSubmitMessage: "Thank you, we received your inscription!",
        success :  false, 
        failure : function() {alert('failure');}  
    });              

  
    $('input, #message').blur(function(){ 
        if ($(this).val() != '' && ($(this).val() == 'Name' || $(this).val() == 'Email' || $(this).val() == 'Your message' )) {
            $(this).val('');
        }
    });
    $('input, #message').click(function(){ 
        if ($(this).val() != '' && ($(this).val() == 'Name' || $(this).val() == 'Email' || $(this).val() == 'Your message' )) {
            $(this).val('');
        }
    });
    $('input, #message').focus(function(){
        $(this).select();
        if ($(this).val() != '' && ($(this).val() == 'Name' || $(this).val() == 'Email' || $(this).val() == 'Your message' )) {
            $(this).val('');
        }
    });
    
// hashchange event detection
    $('.section_heading a, .item_detail').live('click',function(){
        currHref = $(this).attr('href');
        //checkHashChange(currHref);
        
    });

    
//IF YOU ARE USING WRONG BROWSER!!
    if ($.browser.msie && $.browser.version == '6.0')
    {$('<div class="ie-info"></div>').appendTo('div.header-bottom');
        $('.ie-info').append('<p>We are strongly reccomend to update your browser. You can do it from here : <a href="http://www.microsoft.com/windows/internet-explorer/default.aspx">Microsoft Internet Explorer</a>. You can also try to use alternatives like <a href="http://www.mozilla-europe.org/en/firefox/">Firefox</a>, <a href="http://www.google.com/chrome">Chrome</a>, <a href="http://www.apple.com/safari/download/">Safari</a>, <a href="http://www.opera.com/download/">Opera</a>.</p><a href="" class="closeMe">Close</a>');     
    }
    $('.closeMe, .ie-info a').live('click',function(){
        $(this).parent().fadeOut()
    });

// SORT Z-INDEX VALUE OF ALL ELEMENTS ON PAGE
    var zIndexNumber = 1000;
    $('div').each(function() {
        $(this).css('zIndex', zIndexNumber);
        zIndexNumber -= 10;
    });
    
    $('.trigger, .portfolio-nav').css('opacity','0');
    
    Gallery.start();
    

// PREVENT DEFAULT ACTION ON CLICK HERE
    
    //$('.diams-list li a, .openMe, #collapse .section_heading a, .item_detail, .portfolio-nav span, .overlay, .pull_contact, .closeMe, .pull_trigger').live('click', function(e){e.preventDefault();});
    $('.pull_contact, .pull_trigger').live('click', function(e){e.preventDefault();});
// temp disable    
    try {
        ('#blog_content #content p:nth-child(1) a img').parent().css('cursor','default').bind('click', function(e){e.preventDefault()});
    } catch(e) {

    }
    //$('#blog_content #wrapper #content p a img').parent().attr('rel','prettyPhoto');
    $("a[rel^='prettyPhoto']").prettyPhoto({theme: 'dark_square', opacity: 0.8 });
    $("a[rel^='prettyPhotoShowreel']").prettyPhoto({theme: 'dark_square', opacity: 1 });
    
// ROUND MY CORNERS
    
    DD_roundies.addRule('.roundMe, #submit', '10px');
    DD_roundies.addRule('.roundMe, #submit', '10px 10px');
    DD_roundies.addRule('.roundMe, #submit', '10px', true);

// ANIMATE SECTION HEADINGS
    
    $('.section_heading a').hover(
        function(){
            $(this).animate({paddingLeft: '8px',opacity: '1'}, 200);
            $(this).children('.trigger').animate({opacity: '1'}, 400);
            }, function() {
            $(this).animate({paddingLeft: '3px'}, 200);
            $(this).children('.trigger').animate({opacity: '0'}, 200);
    });

// SHOW OVERLAY OVER HOVERED IMG
    
    $('.images-grid a, .portfolio-list li a, #urotator .bigPicture li').live('mouseenter', function(){
        var width = $(this).width();
        var height = $(this).height();
        //alert(width + ' height: ' + height);
        var content = '<div class="overlay"></div>';
        $(this).append(content);
        $('.overlay').css({'width':width,'height':height, 'z-index':'1200'});
        if ($(this).parent().parent().attr('class') == 'portfolio-list'){
            if (!$.browser.msie || $.browser.version != '7.0')
            $(this).parent('li').children('a').children('img').css({'margin': '5px 0 0 5px'});
        }
    });

    $('.images-grid a, .portfolio-list li a, #urotator li').live('mouseleave', function(){
        $('.overlay').remove();
        if ($(this).parent().parent().attr('class') == 'portfolio-list'){
            if (!$.browser.msie || $.browser.version != '7.0')
            $(this).parent('li').children('a').children('img').css({'margin': '6px 0 0 6px'});
        }
    });

// TOGGLE SLIDE 'FILTER BY' ITEM 

    $('.openMe').live('click' , function(e){  
    e.preventDefault();
            var openMe = $('.openMe');
            if ($('.filter-keeper').css('margin-top') == '-235px') {
                slideDownByElemHeight($('.portfolio-list'), $('.filter-keeper'));
                slideDownByElemHeight($('#portfolio'), $('.filter-keeper'));
                slideDownByElemHeight($('.filter-keeper'));  
                $('.filter-keeper').removeClass('filterIsClosed').addClass('filterIsOpen');
                }
            else {
                slideUpByElemHeight($('.portfolio-list'), $('.filter-keeper'));
                slideUpByElemHeight($('#portfolio'), $('.filter-keeper'));
                slideUpByElemHeight($('.filter-keeper'));
                $('.filter-keeper').removeClass('filterIsOpen').addClass('filterIsClosed');
            }
            $(openMe).toggleClass('upArr');
        }
    );
    //$('#blog_content').load('/blog/').show();

// SLIDE/OPEN/CLOSE SECTION ITEM

    $('#collapse .section_heading a').click(
        function(e) {
            handleSection(this, e);
        }
    )
    
// LOAD DETAILS FOR CLICKED PORTFOLIO ITEM

    $('.item_detail').live('click' , function(e){ 
   
        if ($('.filter-keeper').hasClass('filterIsOpen')) {
            slideUpByElemHeight($('.portfolio-list'), $('.filter-keeper'));
            slideUpByElemHeight($('.filter-keeper'));
        }

        $('.filter-keeper').removeClass('filterIsOpen').addClass('filterIsClosed'); 
        loadPorfolioItem($(this).attr('href'), $(this).parent().parent('ul').attr('class'));
    });
    $('.filter-projects li a').live('click',function(){
        loadPorfolioItem($(this).attr('href'), $(this).parent().parent('ul').attr('class'));
    });
    
// SLIDE NEXT/PREV PORTFOLIO CASE STUDY ITEM
    
    $('.spinetv-nav span').live('click', function(e){
        var elementHref = $(this).attr('href');
        $('#spinecontent')
            .fadeOut('slow', function(){
                $('ul.portfolio-list li a[href$="' + elementHref + '"]').click();
                if ($.browser.msie) {
                    elementHref = elementHref.replace('#!', '');
                }
                location.hash = '!'+elementHref;
            });

    });

    $('Z.portfolio-nav span').live('click', function(e){
        console.log('Handling the portfolio-nav span click now');
        var elementInDOM = $('.case_study');
        var elementHref = $(this).attr('href');
        if ($.browser.msie) elementHref = elementHref.substr(elementHref.indexOf('/portfolio'), elementHref.length);
        console.log('elementHref: ' +elementHref);
        $('.show-previous, .show-next').css('visibility','visible');
       
        var elementClass = $(this).attr('class');
        
        elementSplit = elementHref.split('/');
        var elementHref = elementSplit[0] + '/' + elementSplit[1] + '/' + elementSplit[2];
        var nextItem = $('.portfolio-list a[href*="#!' + elementHref + '"]').parent().next('li').children('.item_detail').attr('href');
        var nextHref = undefined;
        
        if(nextItem!=undefined) {
            nextHref = nextItem.replace('#!', '');
        }
        var prevItem = $('.portfolio-list a[href*="#!' + elementHref + '"]').parent().prev('li').children('.item_detail').attr('href');
        var prevHref = undefined;
        if(prevItem!=undefined) {
            prevHref = prevItem.replace('#!', '');
        }
        console.log('nextItem: ' + nextItem + ', prevItem: ' + prevItem);
        window.location = '#!'+elementHref;
        var elementToLoad = elementHref;
        //ie adds site url to variable which ends with '/' so we have one extra

        console.log('elementToLoad set to '+elementToLoad);

        //you can't use variables as a options in .animate() so
        var opts = {};
        margine = 'marginLeft';

        
        ($(this).attr('class') == 'show-previous') ? opts[margine] = '+=1000' : opts[margine] = '-=1000';
          
        //not sure about easing; using another js plugin
        elementInDOM.animate(opts, 500, 'easeInBack' , function(){
            elementInDOM.load(elementToLoad, 
            function(){
                if (prevHref == undefined) { $('.show-previous').css('visibility','hidden')}
                else if (nextHref == undefined) {$('.show-next').css('visibility','hidden')}
                if (elementClass == 'show-previous') {
                    $(this).css('margin-left','-1000px');
                    $(this).animate({marginLeft : '+=1000'}, 100)
                }       
                else {
                    $(this).css('margin-left','1000px');
                    $(this).animate({marginLeft : '-=1000'}, 100);
                }   

                $('.show-previous').attr('href', prevHref);
                $('.show-next').attr('href', nextHref);     
                 console.log('next/prev: nextItem: ' + nextItem + ', prevItem: ' + prevItem + '$(\'.show-previous\').attr(\'href\')' + $('.show-previous').attr('href'));               
            });
        });
    });
    
// OPEN LIGHTBOX ONLY FOR BIG PICTURE
    
    $('.overlay').live('click', function(e){
        if ($(this).parent().parent().attr('class') == 'bigPicture' && $(this).parent().attr('class') == 'pic1b' ) {
            console.log('Trigger lightbox for showreel');
            $(this).parent().children('a').stop().trigger('click');
        }
    });
    
// SLIDE DOWN THE CONTACT INFO
    $('ul.bigPicture li').live('click', function(e) {
        var target = $(this).children('a:first').attr('href');
        if($(this).attr('class')!='pic1b') {
            console.log('Non showreel item clicked: '+$(this).attr('class'));
            if(!$('#portfolio-trigger').hasClass('active')) {
                handleSection($('#portfolio-trigger'), undefined, target);
            } else {
                loadPorfolioItem(target);
            }
            window.location = target;
        }
    });
    
    $('.pull_contact').click(function(e){
        e.preventDefault();
            $('.map_content').empty();
            $('.header-top').slideDown('slow');
            // load maps onclick - speeds up page loading times
            $('.map_content').append('<div id="map_container" style="margin-top: -4px!important; width: 398px!important;"><iframe width="400" height="205" frameborder="0" scrolling="no" marginheight="0" marginwidth="0" id="gmap_frame" src="http://maps.google.com/maps?f=q&amp;source=s_q&amp;hl=en&amp;geocode=&amp;q=udox+london+uk&amp;sll=37.0625,-95.677068&amp;sspn=63.255964,107.138672&amp;ie=UTF8&amp;hq=udox&amp;hnear=Westminster,+London,+United+Kingdom&amp;ll=51.527783,-0.08184&amp;spn=0.006141,0.017123&amp;z=15&amp;iwloc=near&amp;output=embed"></iframe></div>');
    }); 
    $('.pull_trigger').click(function(e){
        $('.header-top').slideUp('slow');
        $('.map_content, .request_info').empty();
    });
    
// LOAD AJAX PAGINATION
    $('#nav-below a, #nav-above a').live('click', function(e){
		e.preventDefault();
		var link = $(this).attr('href');
		$('#content').html('Loading...');
		$('#container').load(link + ' #content', function(){
            console.log('content loaded');
            //$('.entry-content p').hide();
            //$('.entry-content p:nth-child(1)').css('font-style', 'italic').show();
            //$('.entry-content p:nth-child(2)').css('font-style', 'italic').show();
            
            $('.entry-content>*:not(iframe,img)').hide();
            $('.entry-content').children('p:nth-child(1),p:nth-child(2)').show()

            $(".post .entry-content p:nth-child(2)").css('padding','0px 50px 0px 40px');
            $('.entry-content p:nth-child(2)').append('&nbsp; <span class="show-more">View more...</span>');
            $('.show-more').click(function() {
              $(this).parents('.entry-content').children('*').show();
              //$(this).parent().parent().parent().children('.shareMe').css('display','block');
              $(this).hide();
              
            });
        });

	});
    $('.spinetv-expand:not(.expandactive)').live('click',function(e){
        $(this).closest('ul').animate({'height':'300px'}, function(){$(this).css('height', 'auto');})
        $(this).addClass('expandactive');
        return false;
    });
    $('.expandactive').live('click',function(e){
        $(this).closest('ul').animate({'height':'146px'});
        $(this).removeClass('expandactive');
        return false;
    });
    
});

