/**
 * List of flash titles, thumbnails, filenames, and links
 */
var flashList = [];

/**
 * List of images with text and URL's
  */
var imageList = [];

/**
 * This index list is used during inserts to keep track of which thumb
 * will be loaded on next operations. This simulates a database lookup
 */
var flashIndices;

/*
 * Link to the flash video for the flash popup
 */
var popupVideoLink = '';

function BuildFlashIndices()
{
	flashIndices = [];
	for (var i = 0; i < flashList.length; i++)
	{
		flashIndices[i] = i;
	}
}

function phover(){
  if (!document.getElementById) return

  var p = document.getElementsByTagName('p');
  for(var i = 0; i < p.length; i++){
   p[i].onmouseover = function(){
    this.className = 'hover';
   }
   p[i].onmouseout  = function(){
    this.className = '';
   }
  }
}

function flashPopup(videoId) {
	flashWindow=window.open('/flash/RemaxVideo.html','FlashPopup','height=335,width=560,toolbars=no');
	popupVideoLink = flashList[videoId].link;
	selectMovie(videoId, flashList[videoId].title, 'false');
}

function linigerPopup() {
	flashWindow=window.open('/flash/RemaxVideo.html','FlashPopup','height=335,width=560');
	popupVideoLink = "http://remaxsat.edgeboss.net/download/remaxsat/recruiting/home_liniger_large.flv";
}

function GetPopupVideoLink()
{
	return popupVideoLink;
}

function formatItem(videoId, imgUrl, url, title) {

	var innerHTML = 
				'<a href="' + url + '">' + 
				'<img src="' + imgUrl + '" width="58" height="31"/></a>' +
				'<p><a id="videoAncor' + videoId + '" ' + 
				'href="javascript:stopMVid();selectMovie(' + videoId + ', \'' + title + '\', \'true\')" ' +
				'onmouseover="changeText(\''+title+'\')"> <img src="/Portals/0/Skins/JoinREMAX/images/transparent_bg.gif"></a></p>';

	return innerHTML;
}

/**
 * SwfObject function
 * This will change the flash player source to 
 * whatever is passed in to the function.
 */
function selectMovie(videoId, title, autoplay)
{
	autoplay = autoplay ? autoplay : false;
	
	var swf = new SWFObject("/flash/FLVPlayer_Progressive.swf", "FLVPlayer1", "243", "155", "7,0,0,0", "#FFFFFF");
	swf.addParam("salign", "lt");
	swf.addParam("scale", "noscale");
	swf.addParam("quality", "high");
	swf.addParam("wmode", "transparent");
	swf.addParam("FlashVars", "&MM_ComponentVersion=1&skinName=/flash/REMAX_skin&streamName=" + 
								flashList[videoId].filename + "&autoPlay=" + autoplay + "&autoRewind=false");
	swf.write("flashContainer");

	setSelectedVideoStyle(videoId);
	changeText(title, videoId);
	setEnlargeLink(videoId);
}

function setSelectedVideoStyle(videoId)
{
	//Hit each video link and removed the selected video style
	var videoImage;
	var classes;
	for (var i = 0; i < flashIndices.length; i++)
	{
		videoImage = YAHOO.util.Dom.get('videoAncor' + i.toString());
		if (videoImage)
		{
			if (i == videoId)
			{
				videoImage.className = "selectedCarouselItem";
			} else {
				videoImage.className = "";
			}
		}
	}
}


function changeText(title, videoId){	
	YAHOO.util.Dom.get('movieTextContainer').innerHTML = '<p>'+title+'</p>';
}

function setEnlargeLink(videoId) {
	YAHOO.util.Dom.get('flashEnlargeAnchor').href = "javascript:flashPopup(" + videoId + ")";
}

/**
 * Custom inital load handler. Called when the carousel loads the initial
 * set of data items. Specified to the carousel as the configuration
 * parameter: loadInitHandler
 */
var loadInitialItems = function(type, args) {

    var start = args[0];
    var last = args[1]; 

    load(this, start, last);    
};

/**
 * Custom load next handler. Called when the carousel loads the next
 * set of data items. Specified to the carousel as the configuration
 * parameter: loadNextHandler
 */
var loadNextItems = function(type, args) {    

    var start = args[0];
    var last = args[1]; 
    var alreadyCached = args[2];
    
    if(!alreadyCached) {
        load(this, start, last);
    }
};

/**
 * Custom load previous handler. Called when the carousel loads the previous
 * set of data items. Specified to the carousel as the configuration
 * parameter: loadPrevHandler
 */
var loadPrevItems = function(type, args) {
    var start = args[0];
    var last = args[1]; 
    var alreadyCached = args[2];
    
    if(!alreadyCached) {
        load(this, start, last);
    }
};     

/**
 * Custom button state handler for enabling/disabling button state. 
 * Called when the carousel has determined that the previous button
 * state should be changed.
 * Specified to the carousel as the configuration
 * parameter: prevButtonStateHandler
 */
var handlePrevButtonState = function(type, args) {
    var enabling = args[0];
    var leftImage = args[1];
    if(enabling) {
        leftImage.src = "/Portals/0/Skins/JoinREMAX/images/left-enabled.gif";        
    } else {
        leftImage.src = "/Portals/0/Skins/JoinREMAX/images/left-disabled.gif";    
    }
};

/**
 * Custom button state handler for enabling/disabling button state. 
 * Called when the carousel has determined that the next button
 * state should be changed.
 * Specified to the carousel as the configuration
 * parameter: nextButtonStateHandler
 */
var handleNextButtonState = function(type, args) {
    var enabling = args[0];
    var rightImage = args[1];
    if(enabling) {
        rightImage.src = "/Portals/0/Skins/JoinREMAX/images/right-enabled.gif";    
    } else {
        rightImage.src = "/Portals/0/Skins/JoinREMAX/images/right-disabled.gif";
    }
};

/**
 * To simulate out of synch loading, we load these items backwards.
 * This exercises the ability to load items out of sequence.
 */
var load = function(carousel, start, last) {
    for(var i=last; i>=start; i--) {
        if(!carousel.isItemLoaded(i)) {
        //carousel.debugMsg("adding item: " + i);
			var fi = flashIndices[i-1];
			var thumb = flashList[flashIndices[i-1]].thumbnail;
			var title = prefix + flashList[flashIndices[i-1]].title;
			var filename = flashList[i-1].filename;
			carousel.addItem(i, 
						formatItem(flashIndices[i-1], flashList[flashIndices[i-1]].thumbnail, "#",
		                prefix + flashList[flashIndices[i-1]].title, flashList[i-1].filename));
        }
    }
};

var carousel;
var prefix = "";
var pageLoad = function() 
{
    carousel = new YAHOO.extension.Carousel("flash-carousel", 
        {
            numVisible:        3,
            animationSpeed:    0.3,
            animationMethod:   YAHOO.util.Easing.easeBoth,
            scrollInc:         1,
            navMargin:         20,
            size:              flashList.length,
            loadInitHandler:   loadInitialItems,
            prevElement:       "prev-arrow",
            nextElement:       "next-arrow",
            loadNextHandler:   loadNextItems,
            loadPrevHandler:   loadPrevItems,
            prevButtonStateHandler:   handlePrevButtonState,
            nextButtonStateHandler:   handleNextButtonState
        }
    );
};

var clearIt = function(e) {
	BuildFlashIndices();
    carousel.clear();
};
var reloadIt = function(e) {
    prefix+="+";
    BuildFlashIndices();
    carousel.reload();
};
var insert = function(e, before) {
    if(before) {
        _insert(before, "insert-before-name", "insert-before-item");
    } else {
        _insert(before, "insert-after-name", "insert-after-item");
    }
}

/**
 * Illustrates how to insert before or after
 */
var _insert = function(before, nameElem, idxElem) {
    
    var itemNameInput = YAHOO.util.Dom.get(nameElem);
    var newName = itemNameInput.value;

    if(newName === "") {
        YAHOO.util.Dom.get("status").innerHTML = 
                    ''
        return;
    }

    var indexInput = YAHOO.util.Dom.get(idxElem);
    if(indexInput.value === "") {
        YAHOO.util.Dom.get("status").innerHTML = 
                    ''
        return;
    }
    
    var refIdx = parseInt(indexInput.value, 10);
    var ranIdx = Math.floor(Math.random()*18)
    var newImgUrl = flashList[ranIdx].thumbnail;
		var flashFileName = flashList[ranIdx].filename;

    if(before) {
        carousel.insertBefore(refIdx, formatItem(refIdx, newImgUrl, "#", newName, flashFileName));
        updateIndices(refIdx-1, ranIdx);
    } else {
        carousel.insertAfter(refIdx, formatItem(refIdx, newImgUrl, "#", newName, flashFileName));
        updateIndices(refIdx, ranIdx);
    }
    
    YAHOO.util.Dom.get("status").innerHTML = "(Item added)";
};

var updateIndices = function(insertIdx, ranIdx) {
    
    for(var i=flashIndices.length; i >= insertIdx; i--) {
        flashIndices[i] = flashIndices[i-1];
    }
    
    flashIndices[insertIdx] = ranIdx;
};

/***********************************/
/* Image Carousel Code                             */
/***********************************/

/** 
 *  This class controlls scrolling through the images in the imageList
 *  provided on instantiation.  In addition, this class handles adding
 *  event listens, updating urls, and enabling and disabling the 
 *  scroll controls.
 */
function ImageCarouselController(imageList)
{
    var out = document.getElementById("out");

    var self = this;
    var textContainer = YAHOO.util.Dom.get('imageTextContainer');
    var imageContainer = YAHOO.util.Dom.get('imageContainer');

 /**
     *  This method is responsible for generating XHTML for changing out
     *  the larger image, updating a link for that image, and maintaining
     *  an ID to the element for which the small image is bound, so that
     *  event handlers to that image can be added.
     */
    this.formatItem = function(imageId, imgUrl, url, caption)
    {
        return '<a href="' + url + '">' +
            '<img src="' + imgUrl + '" width="58" height="31"/></a>' +
            '<p><a href="#" id="' + imageId + '" >' +
            '<img src="/Portals/0/Skins/JoinREMAX/images/transparent_bg.gif"></a></p>';
    }
	
 /** 
     *  This method simply changes out the caption below the image carousel.
     */
    this.changeText = function (n)
    {
        textContainer.innerHTML = "<p>" + imageList[n].caption + "</p>";
    }

    this.showImage = function(imgUrl, target_url)
    {
        return ('<img src="' + imgUrl + '" border="0"/>');
    }

    this.selectImage = function(n)
    {
        imageContainer.innerHTML = self.showImage(imageList[n].file,
            imageList[n].url);
            
        textContainer.innerHTML = '<p>' + imageList[n].caption + '</p>';
        
        self.setSelectedImageStyle(n);
		
		self.setEnlargeLink(n);
    }

    this.setSelectedImageStyle = function(n)
    {
        //Hit each video link and removed the selected video style
        for (var i = 0; i < imageList.length; i++)
        {
            if (imageList[i].element)
            {
                if (i == n)
                {
                    imageList[i].element.className = "selectedCarouselItem";
                } 
                else
                {
                    imageList[i].element.className = "";
                }
            }
        }
    }
	
	this.setEnlargeLink = function(n) {
		var enlargeImage = YAHOO.util.Dom.get('imageEnlargeAnchor')
		enlargeImage.href = imageList[n].url;
		enlargeImage.target = "_blank";
	}

    /**
     * Custom inital load handler. Called when the carousel loads the initial
     * set of data items. Specified to the carousel as the configuration
     * parameter: loadInitHandler
     */
    this.loadInitialItems = function(type, args) {

        var start = args[0];
        var last = args[1];

        self.load(this, start, last);
    };
    
    /**
     * To simulate out of synch loading, we load these items backwards.
     * This exercises the ability to load items out of sequence.
     */
    this.load = function(carousel, start, last) 
    {
        for(var i = start - 1; i < last; i++)
        {
            var carousel_index = i+1;

            if(!carousel.isItemLoaded( carousel_index ))
            {
                self.addItem(carousel, i, carousel_index);
            }
        }
    };
    
    /**
     *  This method adds one of the image items for the imageList
     *  to the carousel parameter.  The offest is used to determine
     *  which image item to add, and the carousel index parameter
     *  is used to tell the carousel which item position it should
     *  track load previous/next position for.
     */
    this.addItem = function( carousel, offset, carousel_index )
    {
        var caption = imageList[ offset ].caption;
        var file = imageList[ offset ].file;
        var url = imageList[ offset ].url;
        var id = imageList[ offset ].id = "imageAnchor" + carousel_index;

        carousel.addItem(carousel_index,
            self.formatItem(id, file, url, caption));

        imageList[ offset ].element = YAHOO.util.Dom.get(id);

        YAHOO.util.Event.addListener(imageList[ offset ].element, "click",
            function() { self.selectImage( offset ); return false; }, false );

        YAHOO.util.Event.addListener(imageList[ offset ].element, "mouseover",
            function() { self.changeText( offset ); }, false );
    }

    /**
     * Custom load next handler. Called when the carousel loads the next
     * set of data items. Specified to the carousel as the configuration
     * parameter: loadNextHandler
     */
    this.loadNextItems = function(type, args) {

        var start = args[0];
        var last = args[1];
        var alreadyCached = args[2];

        if(!alreadyCached)
        {
            self.load(self.carousel, start, last);
        }
    };

    /**
     * Custom load previous handler. Called when the carousel loads the previous
     * set of data items. Specified to the carousel as the configuration
     * parameter: loadPrevHandler
     */
    this.loadPrevItems = function(type, args)
    {
        var start = args[0];
        var last = args[1];
        var alreadyCached = args[2];

        if(!alreadyCached)
        {
            self.load(self.carousel, start, last);
        }
    };

    /**
     * Custom button state handler for enabling/disabling button state.
     * Called when the carousel has determined that the previous button
     * state should be changed.
     * Specified to the carousel as the configuration
     * parameter: prevButtonStateHandler
     */
    this.handlePrevButtonState = function(type, args)
    {
        var enabling = args[0];
        var leftImage = args[1];

        if(enabling) 
        {
            leftImage.src = "/Portals/0/Skins/JoinREMAX/images/left-enabled.gif";
        }
        else
        {
            leftImage.src = "/Portals/0/Skins/JoinREMAX/images/left-disabled.gif";
        }
    };

    /**
     * Custom button state handler for enabling/disabling button state.
     * Called when the carousel has determined that the next button
     * state should be changed.
     * Specified to the carousel as the configuration
     * parameter: nextButtonStateHandler
     */
    this.handleNextButtonState = function(type, args)
    {
        var enabling = args[0];
        var rightImage = args[1];

        if(enabling)
        {
            rightImage.src = "/Portals/0/Skins/JoinREMAX/images/right-enabled.gif";
        }
        else
        {
            rightImage.src = "/Portals/0/Skins/JoinREMAX/images/right-disabled.gif";
        }
    };

    /**
     *  This method is the point by which the YUI does a call back to
     *  this class when it needs to add more image items to the DOM.
     */
    this.insert = function(e, before)
    {
        if(before)
        {
            _insert(before, "insert-before-name", "insert-before-item");
        }
        else
        {
            _insert(before, "insert-after-name", "insert-after-item");
        }
    }

    /**
     * Illustrates how to insert before or after
     */
    this._insert = function(before, nameElem, idxElem)
    {
        var itemNameInput = YAHOO.util.Dom.get(nameElem);
        var newName = itemNameInput.value;

        if(newName === "")
        {
            YAHOO.util.Dom.get("status").innerHTML = '';
            return;
        }

        var indexInput = YAHOO.util.Dom.get(idxElem);
        if(indexInput.value === "")
        {
            YAHOO.util.Dom.get("status").innerHTML = '';
            return;
        }

        var refIdx = parseInt(indexInput.value, 10);
        var ranIdx = Math.floor(Math.random()*18)
        var newImgUrl = imageList[ranIdx].url;

        if(before)
        {
            carousel.insertBefore(refIdx, 
                formatItem(refIdx, newImgUrl, "#", newName));
        }
        else
        {
            carousel.insertAfter(refIdx, 
                formatItem(refIdx, newImgUrl, "#", newName));
        }

        YAHOO.util.Dom.get("status").innerHTML = "(Item added)";
    };

    YAHOO.util.Event.addListener("insert-after-button", 'click', self.insert, false);
    YAHOO.util.Event.addListener("insert-before-button", 'click', self.insert, true);
} // end swf controller


/**
 *  This call here handles the loading of the ImageCarousel through the
 *  ImageCarouselController once the onload event is called.  In addition
 *  this the ImageCarouselController is set to point to the default
 *  first image.
 */
function ImageCarouselLoader()
{
	var img_controller = new ImageCarouselController(imageList);

	img_controller.carousel = new YAHOO.extension.Carousel("image-carousel",
		{
			numVisible:                 3,
			animationSpeed:             0.3,
			animationMethod:            YAHOO.util.Easing.easeBoth,
			scrollInc:                  1,
			navMargin:                  20,
			size:                       imageList.length,
			loadInitHandler:            img_controller.loadInitialItems,
			prevElement:                "images-prev-arrow",
			nextElement:                "images-next-arrow",
			loadNextHandler:            img_controller.loadNextItems,
			loadPrevHandler:            img_controller.loadPrevItems,
			prevButtonStateHandler:     img_controller.handlePrevButtonState,
			nextButtonStateHandler:     img_controller.handleNextButtonState
		});
		
	img_controller.selectImage(0);
}
	
function CarouselLoader() { 
	phover(); 
	BuildFlashIndices();
	pageLoad(); 
	selectMovie(0, flashList[0].title, 'false'); 
	ImageCarouselLoader();
	InitializeMargaretVideo();
	YAHOO.util.Event.addListener("insert-after-button", 'click', insert, false);
	YAHOO.util.Event.addListener("insert-before-button", 'click', insert, true);
	YAHOO.util.Event.addListener("clear-button", 'click', clearIt);
	YAHOO.util.Event.addListener("reload-button", 'click', reloadIt);
	}
	

/**
 * Cookie methods
 */
function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}

var margaretCode = "";
var margaretFileName = "";
function InitializeMargaretVideo() {
	var divMargaret = getMargaretVideoDiv();
	var cookieName = location.href.replace(/[^a-zA-Z0-9_-]/g,"_");
	
	if (divMargaret)
	{
		margaretCode = divMargaret.innerHTML;
		var regSource = new RegExp(/streamname=([^&]+)&/i);
		var captures = regSource.exec(margaretCode);
		if (captures.length > 0) {
			margaretFileName = captures[1];
			cookieName = margaretFileName.replace(/[^a-zA-Z0-9_-]/g,"_");
		}
	}

	var previouslyViewed = (readCookie(cookieName) !== null);
	createCookie(cookieName, 1);
	if ((previouslyViewed) && (divMargaret))
	{
		stopMVid();
	}
}


function stopMVid(){
	var divMargaret = getMargaretVideoDiv();
	
	if (divMargaret){
		margaretCode = divMargaret.innerHTML;
		divMargaret.innerHTML = "<a href='javascript:ReloadMargaret(\"" + margaretFileName + "\", \"true\")'>" 
			+ "<img src='/Portals/0/Skins/JoinREMAX/images/MargaretPlaceHolder.jpg' alt='Click to restart video' border='0' /></a>";
	}
}

function getMargaretVideoDiv(){
	return YAHOO.util.Dom.get('divMargaret');
}

function old_ReloadMargaret() {
	var divMargaret = YAHOO.util.Dom.get('divMargaret');
	if (divMargaret)
	{
		divMargaret.innerHTML = margaretCode;
	}
}

function ReloadMargaret(fileName, autoplay) {
	autoplay = autoplay ? autoplay : 'false';
	
	var swf = new SWFObject("/flash/FLVPlayer_Progressive.swf", "FLVPlayer2", "230", "420", "7,0,0,0", "#FFFFFF");
	swf.addParam("salign", "lt");
	swf.addParam("scale", "noscale");
	swf.addParam("quality", "high");
	swf.addParam("wmode", "transparent");
	swf.addParam("FlashVars", "&MM_ComponentVersion=1&skinName=/flash/MARGARET_skin&" + 
							"streamName=" + fileName + "&autoPlay=" + autoplay + "&autoRewind=false");
	swf.write("divMargaret");
}
