var projects = {};
var filenames = [];
var SLIDER_WIDTH = 729;
var SLIDER_IMG_MARGIN = 15;
var LEFT_AREA_END = (SLIDER_WIDTH / 2) - 300;
var RIGHT_AREA_START = LEFT_AREA_END + 300;
var sliderImgsWidth = 0;
var sliderEndPosition = 0;
var forceWidthAttempts = 50;
var pageOffsetLeft = 0;
var SHOW_LOADING = 0;
var HIDE_LOADING = 1;
var currentImage = '';
var currentProject = '';
var FADE_IN_ALL = 0;
var FADE_OUT_ALL_BUT_CURRENT = 1;
var cache = [];
var currentOverlay = '';

function getSliderImgWidth() {
    var count = 0;
    $('#preview-slider > div > img').each(function () {
        count += $(this).width() + SLIDER_IMG_MARGIN
    });
    sliderEndPosition = (count - SLIDER_WIDTH - SLIDER_IMG_MARGIN) * -1;
    return count
}
function displayMessage(bgColor, message) {
    if (!$('#message').is(':visible')) {
        $('#message').fadeOut('fast', function () {
            $(this).html('').removeClass().addClass(bgColor).append('<p>' + message + '</p>').fadeIn('normal')
        })
    } else {
        $('#message').contents().fadeOut('normal', function () {
            $(this).parent().removeClass().addClass(bgColor)
        }).html('').append('<p>' + message + '</p>').fadeIn('normal')
    }
}
function previewImagesFade(action, jQ) {
    if (action === FADE_IN_ALL) {
        $(jQ).fadeTo('fast', 1)
    }
    if (action === FADE_OUT_ALL_BUT_CURRENT) {
        $('#preview-slider > div > img:not(".current-image")').animate({
            opacity: 0.6
        }, {
            queue: false,
            duration: 100
        })
    }
}
function loadingDiv(action) {
    if (action === SHOW_LOADING) {
        $('#loading').fadeIn('fast')
    } else {
        $('#loading').css('display', 'none')
    }
}
function onThumbClick() {
    $('#preview-slider > div > img').click(function () {
        if (!$(this).hasClass('current-image')) {
            var filename = $(this).attr('src').replace('thumbs/', 'uploaded/');
            $(this).parent().addClass('loading');
            $('#current-image > img').fadeOut('fast', function () {
                $(this).attr('src', filename).load(function () {
                    $(this).fadeIn('normal', function () {
                        $(this).parent().removeClass('loading')
                    })
                })
            });
            $('#preview-slider > div > img').removeClass();
            $(this).addClass('current-image');
            $('#preview-slider > div > img:not(".current-image")').animate({
                opacity: 0.6
            }, {
                queue: false,
                duration: 100
            })
        }
    })
}
function closeOverlay() {
    $('.overlay').fadeOut('fast');
    $('#current-image, #preview-slider').fadeIn('fast');
    $('.overlay-link').removeClass('active-link');
    $('#video-content td').html('');
    currentOverlay = ''
}
function change(input) {
    var output = "";
    var chr1, chr2, chr3 = "";
    var enc1, enc2, enc3, enc4 = "";
    var i = 0;
    var keyStr = "ABCDEFGHIJKLMNOP" + "QRSTUVWXYZabcdef" + "ghijklmnopqrstuv" + "wxyz0123456789+/" + "=";
    var base64test = /[^A-Za-z0-9\+\/\=]/g;
    if (base64test.exec(input)) {
        alert("There were invalid base64 characters in the input text.\n" + "Valid base64 characters are A-Z, a-z, 0-9, '+', '/',and '='\n" + "Expect errors in decoding.")
    }
    input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
    do {
        enc1 = keyStr.indexOf(input.charAt(i++));
        enc2 = keyStr.indexOf(input.charAt(i++));
        enc3 = keyStr.indexOf(input.charAt(i++));
        enc4 = keyStr.indexOf(input.charAt(i++));
        chr1 = (enc1 << 2) | (enc2 >> 4);
        chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
        chr3 = ((enc3 & 3) << 6) | enc4;
        output = output + String.fromCharCode(chr1);
        if (enc3 != 64) {
            output = output + String.fromCharCode(chr2)
        }
        if (enc4 != 64) {
            output = output + String.fromCharCode(chr3)
        }
        chr1 = chr2 = chr3 = "";
        enc1 = enc2 = enc3 = enc4 = ""
    } while (i < input.length);
    return unescape(output)
}
function embedVideo(videoId) {
    var options = videoId.split('-');
    filename  = BASE_URL+'portfolio/videos/'+options[0];
    vidWidth  = options[1];
    vidHeight = options[2];
    
    var vidType = filename.split('.').pop();
    
    if (vidType === 'mov') {
        var embedContent = '<embed src="'+filename+'" width="'+vidWidth+'" height="'+vidHeight+'">';
    } else if (vidType === 'mp4') {
        var embedContent = '<OBJECT CLASSID="clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B" CODEBASE="http://www.apple.com/qtactivex/qtplugin.cab" WIDTH="'+vidWidth+'" HEIGHT="'+vidHeight+'" >';
        embedContent += '<PARAM NAME="src" VALUE="'+filename+'"><PARAM NAME="autoplay" VALUE="true">';        
        embedContent += '<EMBED SRC="'+filename+'" TYPE="image/x-macpaint" PLUGINSPAGE="http://www.apple.com/quicktime/download" WIDTH="'+vidWidth+'" HEIGHT="'+vidHeight+'" AUTOPLAY="true"></EMBED>';
        embedContent += '</OBJECT>';
    }
    
    $('#video-content td').html(embedContent);
}
window.onload = function () {
    var safari = $.browser.safari;
    $.preLoadImages = function (path, images) {
        var args_len = images.length;
        for (var i = args_len; i--;) {
            var cacheImage = document.createElement('img');
            cacheImage.src = 'portfolio/' + path + '/' + images[i];
            cache.push(cacheImage)
        }
    };
    jQuery.preLoadImages('thumbs', filenames);
    jQuery.preLoadImages('uploaded', filenames);
    onThumbClick();
    $('.project-link').click(function () {
        var projectName = $(this).html();
        if (currentProject === projectName) {
            return false
        } else {
            currentProject = projectName
        }
        $('#preview-slider > div > img').fadeOut('normal');
        $('#current-image > img').fadeOut('slow', function () {
            var filename = structure[projectName]['images'][0].filename;
            $(this).attr('src', 'portfolio/uploaded/' + filename).load(function () {
                $(this).fadeIn('normal')
            });
            var sliderImgs = '';
            for (var image in structure[projectName]['images']) {
                var imageObj = structure[projectName]['images'][image];
                sliderImgs += '<img src="portfolio/thumbs/' + imageObj.filename + '" alt="' + imageObj.image_label + '" ' + imageObj.width_height + '/>'
            }
            $('#preview-slider > div').html(sliderImgs).fadeIn('fast', function () {
                sliderImgsWidth = getSliderImgWidth()
            });
            $('#preview-slider > div').css('left', '0px');
            $('#preview-slider > div > img').hover(function () {
                $(this).fadeTo('fast', 1)
            }, function () {
                $('#preview-slider > div > img:not(".current-image")').animate({
                    opacity: 0.6
                }, {
                    queue: false,
                    duration: 100
                })
            });
            onThumbClick();
            $('#preview-slider > div > img:first').addClass('current-image')
        });
        $('.project-link').removeClass('active-menu-item');
        $(this).addClass('active-menu-item');
        forceWidthAttemps = 50;
        return false
    });
    $('#preview-slider > div > img').hover(function () {
        previewImagesFade(FADE_IN_ALL, this)
    }, function () {
        previewImagesFade(FADE_OUT_ALL_BUT_CURRENT, this)
    });
    $('#current-image > img').fadeIn('normal');
    d = new Date();
    $('#copyright').prepend('&copy; ' + d.getFullYear() + ' Liz Michael');
    sliderImgsWidth = getSliderImgWidth();
    $('#contact-link').toggle(function () {
        $('#contact').slideDown('fast')
    }, function () {
        $('#contact').slideUp('fast')
    });
    $('#intro').click(function () {
        $(this).fadeOut('slow')
    });
    $('#invert').toggle(function () {
        $('body, #current-image').animate({
            backgroundColor: '#090909'
        }, 400)
    }, function () {
        $('body, #current-image').animate({
            backgroundColor: '#ffffff'
        }, 400)
    });
    currentProject = $('#menu-items li:eq(0) a').html();
    $('#menu-items li:first a').addClass('active-menu-item');
    $('#intro-img').fadeIn('normal');
    $('#preview-slider > div > img:first').addClass('current-image');
    $('#preview-slider').live('mousemove', function (e) {
        if (sliderImgsWidth < SLIDER_WIDTH) {
            return
        }
        var slider = $(this);
        var pos = (e.pageX - slider.offset().left);
        if (pos <= LEFT_AREA_END) {
            pos = '0px'
        } else if (pos >= RIGHT_AREA_START) {
            pos = sliderEndPosition + 'px'
        } else {
            slider.find('div').stop();
            return
        }
        slider.find('div').animate({
            left: pos
        }, {
            queue: false,
            duration: 1600
        })
    });
    $('#preview-slider').live('mouseleave', function () {
        $(this).find('div').stop()
    });
    $('.overlay-link').click(function () {
        var thisOverlay = $(this).attr('id').split('-').pop();
        if (currentOverlay === thisOverlay) {
            $(this).html(thisOverlay);
            closeOverlay();
            return
        } else {
            $('.overlay').css('z-index', '1');
            $('#current-image, #preview-slider').fadeOut('fast');
            $('#overlay-' + thisOverlay).css('z-index', '9999').fadeIn('fast', function () {
                $('.overlay').not(this).hide()
            });
            if (currentOverlay) {
                $('.overlay-link').not(this).each(function () {
                    $(this).html($(this).attr('rel'))
                })
            }
            $(this).html('gallery');
            currentOverlay = thisOverlay
        }
        $('.overlay-link').removeClass('active-menu-item');
        $(this).addClass('active-menu-item')
    });
    $('.close-overlay').click(function () {
        closeOverlay()
    });
    $('#video-menu li a').click(function () {
        var vidId   = $(this).attr('id');

        embedVideo(vidId);
        $('#video-menu a').removeClass('active-menu-item');
        $(this).addClass('active-menu-item');
        return false;
    })
}