/*global DOMAssistant, $, $$ */

var left_col_dir = '/content/images/left_column/';
var menu_array = new Array("white", "green", "black");


//How many different patterns there are
var p1_length = 3;
var p2_length = 3;
var p3_length = 3;

//Declare vertical offset vars
var yOffset_max = 200;
var p1_yOffset = 0 + Math.floor(Math.random() * yOffset_max);
var p2_yOffset = 0 + Math.floor(Math.random() * yOffset_max);
var p3_yOffset = 0 + Math.floor(Math.random() * yOffset_max);

//Modifiers for parallax speeds
var p1_modifier = 0.02;
var p2_modifier = 0.06;
var p3_modifier = 0.1;

var ie6 = false;

var beginX = 0;
var endX = 0;

var draggable = false;

$(document).ready(function() {
    //Hides and fades out elements
    $('td#left-column div.menu').hide();
    $('td#left-column div#left-column-cover').delay(200).fadeOut().remove();

    $('td#footer a').attr('target', '_blank');
    $('td#left-column div.menu').css({ 'background': 'transparent' });

    //Stretch sub nav image
    if ($('td#left-column div.menu img.sub-menu-image').length > 0) {
        $('td#left-column div.menu img.sub-menu-image').css('height', ($('td#left-column div.menu ul.sub-menu').children().length * 20 + 150) + "px");
    }

    if ($.browser.msie && $.browser.version.substr(0, 1) < 7) {
        ie6 = true;
        loadThumbnail(randomizeMenuBackground(left_col_dir + 'menu_bg/menu_bg_', '_ie6.png', menu_array.length - 1, true), 'td#left-column div.menu');
    }
    else {
        $('td#left-column span#base, td#left-column span#middle, td#left-column span#top').css({ 'left': '0', 'top': '0' });

        updateSpanBackgroundPositions();

        $(window).scroll(updateSpanBackgroundPositions);

        //Randomize backgrounds
        loadThumbnail(randomizeMenuBackground(left_col_dir + 'menu_bg/menu_bg_', '.png', menu_array.length), 'td#left-column div.menu');
        startLoadingThumbnails(randomizeBackground(left_col_dir + 'pattern_3/p_3_', '.png', p3_length), 'td#left-column span#top');
    }

    //Hover checks
    if ($("td#body a.featured").length > 0) {
        createHover($("td#body a.featured"));
    }

    if ($("td#body fieldset input.button").length > 0) {
        createHover($("td#body fieldset input.button"));
    }

    //Art gallery
    var ulParent = $('td#body div.stream-container');
    var ul = $('td#body div.stream-container ul');

    if (ul.length > 0) {
        var liCount = ul.children().size();
        ulParent.css('height', ul.children('li:first-child').outerHeight() + 'px');
        ul.css({ 'width': (liCount * ul.children('li:first-child').outerWidth()) + 'px' });

        $('body').append('<span class="art-arrow-left">&nbsp;</span><span class="art-arrow-right">&nbsp;</span><span style="display:none;" class="art-loading">&nbsp;</span>');
        $('span.art-arrow-left, span.art-arrow-right', '#tdbody').hide();

        var hrefs = '';
        var checkFirstAnchor = true;
        $('td#body div.stream-container ul li a').each(function() {
            if (checkFirstAnchor) {
                checkFirstAnchor = false;
                $(this).addClass('selected');
            }
            $(this).attr('href', 'javascript:checkIfArtIsClicked("' + $(this).attr('href') + '");');
        });

        if (ul.outerWidth() > 650) {
            draggable = true;
            ulParent.mousedown(function(event) {
                beginX = event.pageX;

                $('body').bind('mouseup', function() {
                    stopDragging(); 
                });

                $(this).css({
                    cursor: 'grabbing',
                    cursor: '-moz-grabbing'
                }).data('down', true).data('x', event.clientX).data('scrollLeft', this.scrollLeft);

                startDragging();

                return false;

            }).mouseup(function(e) {
                endX = e.pageX;
                $(this).css({
                    cursor: 'grab',
                    cursor: '-moz-grab'
                }).data('down', false);

                stopDragging(e.pageX, e.pageY);
            }).mousemove(function(event) {
                $('td#body div.stream-container ul li a', 'td#body div.stream-container ul li').css({ cursor: 'pointer', cursor: 'hand' });

                if ($(this).data('down') == true && (event.pageX > beginX + 10 || event.pageX < beginX - 10)) {
                    $('td#body div.stream-container ul li a', 'td#body div.stream-container ul li').css({ cursor: 'grabbing', cursor: '-moz-grabbing' });
                    $('span.art-arrow-left, span.art-arrow-right', 'body').hide();
                }
                else {
                    $('span.art-arrow-left', 'body').css({ 'left': (event.pageX - 23) + 'px', 'top': (event.pageY) + 'px' });
                    $('span.art-arrow-right', 'body').css({ 'left': (event.pageX + 17) + 'px', 'top': (event.pageY) + 'px' });
                }
            });

            ul.hover(function(e) {
                $('span.art-arrow-left, span.art-arrow-right', 'body').show();
            }, function(e) {
                $('span.art-arrow-left, span.art-arrow-right', 'body').hide();
            }).mouseenter(function(e) {
                $('span.art-arrow-left, span.art-arrow-right', 'body').show();
            }).mouseleave(function(e) {
                $('span.art-arrow-left, span.art-arrow-right', 'body').hide();
            });

            $('span.art-arrow-left, span.art-arrow-right').hover(function(event) { event.stopPropagation(); }).mousemove(function(event) { event.stopPropagation(); });
            $('span.art-loading').hide();
        }
    }

});

function updateSpanBackgroundPositions() {
    /*var posY = 0;
    if (document.documentElement && (document.documentElement.scrollTop)) {
        browserTopY = document.documentElement.scrollTop;
    } else {
        browserTopY = document.body.scrollTop;
    }*/
    var posY = (document.documentElement.scrollTop) ? document.documentElement.scrollTop : document.body.scrollTop; //window.pageYOffset;
    $('td#left-column span#base').css({ 'background-position': '0 ' + (p1_yOffset - posY * p1_modifier) + 'px' });
    $('td#left-column span#middle').css({ 'background-position': '0 ' + (p2_yOffset - posY * p2_modifier) + 'px' });
    $('td#left-column span#top').css({ 'background-position': '0 ' + (p3_yOffset - posY * p3_modifier) + 'px' });
}

function startDragging()
{
	var ulParent = $('td#body div.stream-container');
	
	$('body').bind('mouseup',function (e){
		$('td#body div.stream-container').data('down', false);
		stopDragging(e.pageX, e.pageY);
	});
	
	$('body').bind('mousemove',function (event) {	
		
		if ($('td#body div.stream-container').data('down') == true) 
		{
			var newLeft = ulParent.data('scrollLeft') + ulParent.data('x') - event.clientX;
			
			if (newLeft > ulParent.children('ul').outerWidth() - ulParent.outerWidth()-7)
				newLeft = ulParent.children('ul').outerWidth() - ulParent.outerWidth()-7;
			
			if (newLeft < 0)
				newLeft = 0;
			
			$('td#body div.stream-container').scrollLeft(newLeft);
		}
	});
}

function stopDragging(pX,pY)
{
	$('body').unbind('mousemove');
	
	if (pX)
		if (pX > 350 && pX < 1000)
			$('span.art-arrow-left, span.art-arrow-right', 'body').show();
	
	$('td#body div.stream-container ul li a','td#body div.stream-container ul li').css({cursor: 'pointer',cursor: 'hand'});
}

function checkIfArtIsClicked(href)
{
	if (draggable)
	{
		if (endX > beginX-10 && endX < beginX+10)
		{
			loadArt(href, $('td#body div.image-container'));

			$('td#body div.stream-container ul li a').each(function (){ 
		        if ($(this).attr('href') == 'javascript:checkIfArtIsClicked("' + href + '");')
		        	$(this).addClass("selected");
		        else
		        	$(this).removeClass("selected");
		    });
		}
	}
	else
	{
		loadArt(href, $('td#body div.image-container'));

		$('td#body div.stream-container ul li a').each(function (){ 
	        if ($(this).attr('href') == 'javascript:checkIfArtIsClicked("' + href + '");')
	        	$(this).addClass("selected");
	        else
	        	$(this).removeClass("selected");
	    });
	}
}
var initialLoad = true;
function loadArt (str, destination) {
	//Create a placeholder img
    var img = new Image();
    
    if (initialLoad)
    {
    	initialLoad = false;
    	$('span.art-loading').css({'left' : (350+325-16)+'px', 'top' : (80+$('td#body div.image-container img').innerHeight()/2-8)+'px'}).show();
    }
    else
    {

    	$('span.art-loading').show();
    }
    	
    $(img).load(function () {
    	destination.css('height',destination.innerHeight()+"px");
        $(this).css('display', 'none'); // .hide() doesn't work in Safari when the element isn't on the DOM already
        $(this).hide();
        var referenceHeight = destination.outerHeight();
		destination.html('');
		destination.append($(this));
		
		if ($(this).innerWidth() > 650)
			$(this).css('width','650px');
		
		destination.animate({'height': $(this).outerHeight()});
		
		$(this).show();
		$('span.art-loading').css({'left' : (350+325-16)+'px', 'top' : (80+$(this).innerHeight()/2-8)+'px'}).hide();
		
    }).error(function () {
        // notify the user that the image could not be loaded
    }).attr('src', str);
}

function startLoadingThumbnails (str, destination) {
	//Create a placeholder img
	
    var img = new Image();
    $(img).load(function () {
        $(this).css('display', 'none'); // .hide() doesn't work in Safari when the element isn't on the DOM already
        $(this).hide();

		if (!ie6)
		    $(destination).css({ 'background-image': 'url(' + $(this).attr('src') + ')', 'background-repeat': 'no-repeat' });
		else
			$(destination).css({'background-image' : 'url(' + $(this).attr('src') + ')','background-repeat' : 'no-repeat'});

        loadSecondThumbnail(randomizeBackground(left_col_dir + 'pattern_2/p_2_', '.png', p2_length), 'td#left-column span#middle');
		
		$(destination).fadeIn();
		$(this).remove();
    }).error(function () {
        // notify the user that the image could not be loaded
    }).attr('src', str);
}

function loadSecondThumbnail(str, destination)
{
	//Create a placeholder img
	var img = new Image();
	$(img).load(function () {
	    $(this).css('display', 'none'); // .hide() doesn't work in Safari when the element isn't on the DOM already
	    $(this).hide();
	    
		if (!ie6)
			$(destination).css({'background-image' : 'url(' + $(this).attr('src') + ')', 'background-repeat' : 'no-repeat'});
		else
			$(destination).css({'background-image' : 'url(' + $(this).attr('src') + ')', 'background-repeat' : 'no-repeat'});

        loadThumbnail(randomizeBackground(left_col_dir + 'pattern_1/p_1_', '.png', p1_length), 'td#left-column span#base');
	
		$(destination).fadeIn();
		$(this).remove();
	}).error(function () {
	    // notify the user that the image could not be loaded
	}).attr('src', str);
}

function loadThumbnail (str, destination) {
	//Create a placeholder img
    var img = new Image();
    $(img).load(function() {
        $(this).css('display', 'none'); // .hide() doesn't work in Safari when the element isn't on the DOM already
        $(this).hide();

        if (!ie6) {
            $(destination).css({ 'background-image': 'url(' + $(this).attr('src') + ')', 'background-repeat': 'no-repeat' });
        } else {
            $(destination).css({ 'background-image': 'url(' + $(this).attr('src') + ')', 'background-repeat': 'no-repeat' });
        }

        $(destination).fadeIn();
        $(this).remove();
    }).error(function() {
        // notify the user that the image could not be loaded
    }).attr('src', str);
}

function randomizeBackground(prefix, suffix, total) {
    return prefix + String(Math.floor(Math.random() * total) + 1) + suffix;
}

function randomizeMenuBackground(prefix,suffix,total,isMenu)
{
    var menustring = menu_array[Math.floor(Math.random() * total)];
    $('td#left-column div.menu').addClass(menustring);
    return prefix + menustring + suffix;
}

function addQuicktime(_width, _height, _mov, _destination)
{
	if ($.browser.msie && $.browser.version.substr(0, 1) < 7)
	{
		_destination.html('');
		_destination.append('<OBJECT id="movie-container" width="' + _width + '" height="' + _height + '" classid="clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B" codebase="http://www.apple.com/qtactivex/qtplugin.cab#version=7,3,0,0"><PARAM value="' + _mov + '?width=' + _width + '&amp;height=' + _height + '" name="src" /><PARAM value="true" name="controller" /><PARAM value="false" name="showlogo" /><PARAM value="true" name="cache" /><PARAM value="#000000" name="bgcolor" /><PARAM value="true" name="autostart" /><PARAM value="true" name="saveembedtags" /><PARAM value="true" name="postdomevents" /><PARAM value="true" name="kioskmode" /></OBJECT');
	}
	else
	{
		_destination.html('');
		_destination.append('<object width="' + _width + '" height="' + _height + '" codebase="http://www.apple.com/qtactivex/qtplugin.cab#version=7,3,0,0" classid="clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B"><param value="' + _mov + '?width=' + _width + '&amp;height=' + _height + '" name="src"><object width="' + _width + '" height="' + _height + '" type="video/quicktime" data="' + _mov + '?width=' + _width + '&amp;height=' + _height + '"><param value="true" name="controller"><param value="false" name="showlogo"><param value="aspect" name="scale"><param value="true" name="cache"><param value="#000000" name="bgcolor"><param value="true" name="autostart"><param value="true" name="saveembedtags"><param value="true" name="postdomevents"><param value="true" name="kioskmode" /></object><param value="true" name="controller"><param value="false" name="showlogo"><param value="true" name="cache"><param value="#000000" name="bgcolor"><param value="true" name="autostart"><param value="true" name="saveembedtags"><param value="true" name="postdomevents"><param value="true" name="kioskmode" /></object>');
	}
}

function createHover(obj)
{
	obj.hover(
		function () {
			$(this).addClass('hover');
		}, function () {
			$(this).removeClass('hover');
		}
	);
}