/**
 * @author Alex Billington, 2009, for yehrintong.com
 */
// google analytics
var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
try {
    var pageTracker = _gat._getTracker("UA-9162850-1");
    pageTracker._trackPageview();
} 
catch (err) {
}

var disable = false;

function loadPageImage(imgs){
    var temp = imgs.pop();
    var img = new Image();
    
    // hide the list element before displaying
    $(temp['elem']).addClass('hide');
    
    // process this image 
    $(temp['elem']).css('background', 'url(' + temp["back"] + ') 0 0 no-repeat');
    $(temp['elem']).css('cursor', 'pointer');
    $(img).load(function(){
        $(temp['elem']).append(img); // inserts the image into the placeholder
        // fade in when loaded
        $(temp['elem']).fadeIn(500);
        
        // show background CSS image on hover
        $(img).hover(function(){
            var src = $(img).attr('src');
            $(img).fadeTo(500, 0.33);
        }, function(){
            $(img).fadeTo(500, 1);
        });
        
        // event for loading the large image
        $(img).click(function(){
            if (!disable) {
                disable = true;
                $('#loader').addClass('loading');
                $('body').css('cursor', 'wait'); 
                $("#next").deactivate();
                $("#prev").deactivate();
                var currentImage = $(this).attr('src');
                var hiresImage = currentImage.replace(/img\/thumb\//, 'img\/hi-res\/');
                var img = new Image();
                $("#main").fadeOut(1000);
                $(img).load(function(){
                    $("#hires_placeholder").hide();
                    $('#hires_placeholder').html(this); // inserts the image into the placeholder
                    if (temp['left']) {
                        $(this).css('float', 'left');
                        $(this).css('margin-left', '20px');
                    }
                    $("#hires_placeholder").fadeIn(500, function(){
                        disable = false;
                        $("#next").deactivate();
                        $("#prev").deactivate();
                        $("#close").activate();
                        $('#loader').removeClass('loading');
                        $('body').css('cursor', 'default');
                    });
                }).error(function(){
                    // image not found, ignore gracefully
                    $('#loader').removeClass('loading');
                    $('body').css('cursor', 'default');
                }).attr('src', hiresImage);
                return false;
            }
        });
        
        if (imgs.length > 0) {
            // load the next one in recursively
            loadPageImage(imgs);
        }
        else {
            // finished loading all
            $('#loader').removeClass('loading');
            $('body').css('cursor', 'default');
            $(temp['elem']).parent('ul').addClass('loaded');
        }
    }).attr('src', temp['fore']);
}


function loadPageImages(section, page){
    var imgs = new Array();
    var cnt = 0;
    // build an array of all the thumbnails and hover images to load for this page, if we haven't already (check using ".loaded"):
    if ((!$('#' + section + '_' + page).is('.loaded')) && (section == 'archive' || section == 'portfolio')) {
        $('#loader').addClass('loading');
        $('body').css('cursor', 'wait');
        $('#' + section + '_' + page + ' li').each(function(){
            if ($(this).children().is('a')) {
                var src = ($(this).children("a").attr('href'));
                var dets = {
                    fore: src.replace(/img\/hi-res\/([a-zA-Z0-9]+).*/, 'img\/thumb\/$1.jpg'),
                    back: src.replace(/img\/hi-res\/([a-zA-Z0-9]+).*/, 'img\/thumb\/$1_text.gif'),
                    left: $(this).children("a").is(".left"),
                    elem: this
                };
                imgs[cnt] = dets;
                cnt++;
            }
        });
        // flip the array and pop each element off the end, processing one at a time
        imgs.reverse();
        loadPageImage(imgs);
    }
}

function showPage(showPage, showSection, hidePage, hideSection){
    // called inbetween fadeout and fadein
    if ((hidePage != null) && (hideSection != null)) {
        $('#' + hideSection + '_' + hidePage).addClass('hide');
    }
    $('#' + showSection + '_' + showPage).removeClass('hide');
    $('#main').fadeIn(1000, function(){
        loadPageImages(showSection, showPage);
    });
}

function getNumPagesInSection(section){
    var splitStr = '';
    pages = 0;
    $('#imgbox ul').each(function(i){
        splitStr = $(this).attr("id").split(/_/);
        if (splitStr[0] == section) {
            pages++;
        }
    });
    return pages;
}

function getPageInfo(){
    var pages = 0;
    var curPage = 1;
    var curSect = false;
    
    var tmpSect = false;
    var tmpPage = 1;
    
    $('#imgbox ul').each(function(i){
        var splitStr = $(this).attr('id').split(/_/);
        // if we still haven't found the currently selected section
        if ((splitStr[0] != tmpSect) && (!curSect)) {
            // it's a new section
            pages = 0;
            tmpSect = splitStr[0];
        }
        else 
            if (splitStr[0] != tmpSect) {
                // it's a new section and we have the number of pages in the requested section, return
                curPage = parseInt(curPage);
                pages = parseInt(pages);
                return {
                    current: curPage,
                    section: curSect,
                    numPages: pages
                };
            }
        tmpPage = (splitStr[1]);
        pages++;
        // only one will be visible at one time
        if (!$(this).hasClass("hide")) {
            curSect = tmpSect;
            curPage = tmpPage;
        }
    });
    // if it was the last section
    curPage = parseInt(curPage);
    pages = parseInt(pages);
    // update page display
    return {
        current: curPage,
        section: curSect,
        numPages: pages
    };
}

function updateButtons(newPageNum, totalPages, section){
    if ((newPageNum == null) || (totalPages == null) || (section == null)) {
        var pageInfo = getPageInfo();
        newPageNum = pageInfo['current'];
        totalPages = pageInfo['numPages'];
        section = pageInfo['section'];
    }
    $('.section').each(function(){
        if ($(this).attr('id') == section) {
            $(this).deactivate();
        }
        else 
            if ($(this).is('.disabled')) {
                $(this).activate();
            }
    });
    
    // hide next and previous buttons accordingly.
    if (newPageNum == 1) {
        $('#prev').deactivate();
    }
    else {
        if ($('#prev').is(".disabled")) {
            $('#prev').activate();
        }
    }
    if (newPageNum == totalPages) {
        $('#next').deactivate();
    }
    else {
        if ($('#next').is(".disabled")) {
            $('#next').activate();
        }
    }
}

function gotoPage(page, section){
    // if section not specified, just keep the same one
    if (!disable) {
        disable = true;
        var pageInfo = getPageInfo();
        if (section == null) {
            section = pageInfo['section'];
        }
        var newPage = false;
        // fade out a background picture if one's displayed
        if (!($('#hires_placeholder').is(':hidden'))) {
            //  don't revert to previous page first ##
            // $('#main').show();
              $('#hires_placeholder').fadeOut(1000);
              $('#close').deactivate();
        }
        if (page == 'next') {
            newPage = pageInfo['current'] + 1;
        }
        else 
            if (page == 'prev') {
                newPage = pageInfo['current'] - 1;
            }
            else {
                // direct
                if ((pageInfo['current'] != parseInt(page)) || (pageInfo['section'] != section)) {
                    newPage = parseInt(page);
                }
            }
        
        if (newPage) {
            $('#main').fadeOut(1000, function(){
                disable = false;
                showPage(newPage, section, pageInfo['current'], pageInfo['section']);
                numPages = getNumPagesInSection(section);
                updateButtons(newPage, numPages, section);
            });
        }
    }
}

jQuery.fn.deactivate = function(speed){
    if (speed == null) {
        speed = 0;
    }
    $(this).fadeTo(0, 0.2);
    $(this).addClass('disabled');
    $(this).removeClass('p');
};

jQuery.fn.activate = function(speed){
    if (speed == null) {
        speed = 0;
    }
    $(this).fadeTo(0, 1);
    $(this).removeClass('disabled');
    $(this).addClass('p');
};

$(document).ready(function(){
    // init
    $("#close").deactivate();
    showPage(1, "portfolio");
    updateButtons(1, 2, 'portfolio'); // init with > 1 page (number irrelevant)
    // adjust title spacing if necessary for lower res
    if (screen.width <= 1024) {
        $('#yehrin_tong').css('margin-right', '40px');
        $('#archive').css('margin-right', '40px');
        $('#portfolio').css('margin-right', '40px');
        $('#info').css('margin-right', '40px');
        $('#contact').css('margin-right', '40px');
        $('#head').css('width', '935px');
    }
    
    // hover effect for .h
    $('.h').hover(function(){
        if (!$(this).is('.disabled')) {
            $(this).fadeTo(300, 0.2);
        }
    }, function(){
        if (!$(this).is('.disabled')) {
            $(this).fadeTo(300, 1);
        }
    });
    
    // pagination events
    $('#next').click(function(){
      if (!disable) {
        $('body').css('cursor', 'wait');
            if (!$(this).is(".disabled")) {
                gotoPage('next');
            }
            return false;
        }
    });
    
    $('#prev').click(function(){
        if (!disable) {
            if (!$(this).is(".disabled")) {
                gotoPage('prev');
            }
            return false;
        }
    });
    
    $('#close').click(function(){
        if (!disable) {
            disable = true;
            if (!$(this).is(".disabled")) {
                $("#main").fadeIn(1000);
                $("#close").deactivate();
                $("#hires_placeholder").fadeOut(1000, function(){
                    updateButtons();
                    disable = false;
                });
            }
        }
    });
    
    // closing large images
    $('#hires_placeholder').click(function(){
        if (!disable) {
            disable = true;
            $("#main").fadeIn(1000);
            $("#hires_placeholder").fadeOut(1000, function(){
                $("#close").deactivate();
                updateButtons();
                disable = false;
            });
        }
    });
    // sections nav, goto p1 of section with that ID
    $('.section').click(function(){
        if (!$(this).is('.disabled')) {
            gotoPage(1, $(this).attr("id"));
        }
        // reenable form input just in case
        if ($(this).is('#contact')) {
            $('input, textarea').removeAttr('disabled')
            $('#name, #message, #email').val('');
            $('#res').hide();
            $('#submit').show();
        }
    });
    
    $('#res a').click(function(){
        $('input, textarea').removeAttr('disabled');
        $('#name, #message, #email').val('');
        $('#res').hide();
        $('#submit').show();
        return false;
    });
    
    // form validation
    $("#enquiry_form").validate({
        rules: {
            name: {
                required: true
            },
            message: {
                required: true
            },
            email: {
                required: true,
                email: true
            }
        },
        messages: { // no messages, just css error
            name: {
                required: ""
            },
            message: {
                required: " "
            },
            email: {
                required: " ",
                email: ""
            }
        },
        submitHandler: function(form){
            $('#submit').hide();
            $('#loader').addClass('loading');
            $('input, textarea').attr('disabled', 'true');
            $.post("m.php", {
                name: $('#name').val(),
                email: $('#email').val(),
                message: $('#message').val()
            }, function(data){
                $('#res').show();
                $('#loader').removeClass('loading');
            });
        }
    });
    $("input, textarea").blur(function(){
        $(this).valid();
    });
});
