var BrowserDetect = {
	init: function () {
		this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
		this.version = this.searchVersion(navigator.userAgent)
			|| this.searchVersion(navigator.appVersion)
			|| "an unknown version";
		this.OS = this.searchString(this.dataOS) || "an unknown OS";
	},
	searchString: function (data) {
		for (var i=0;i<data.length;i++)	{
			var dataString = data[i].string;
			var dataProp = data[i].prop;
			this.versionSearchString = data[i].versionSearch || data[i].identity;
			if (dataString) {
				if (dataString.indexOf(data[i].subString) != -1)
					return data[i].identity;
			}
			else if (dataProp)
				return data[i].identity;
		}
	},
	searchVersion: function (dataString) {
		var index = dataString.indexOf(this.versionSearchString);
		if (index == -1) return;
		return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
	},
	dataBrowser: [
		{ 	string: navigator.userAgent,
			subString: "OmniWeb",
			versionSearch: "OmniWeb/",
			identity: "OmniWeb"
		},
		{
			string: navigator.vendor,
			subString: "Apple",
			identity: "Safari"
		},
		{
			prop: window.opera,
			identity: "Opera"
		},
		{
			string: navigator.vendor,
			subString: "iCab",
			identity: "iCab"
		},
		{
			string: navigator.vendor,
			subString: "KDE",
			identity: "Konqueror"
		},
		{
			string: navigator.userAgent,
			subString: "Firefox",
			identity: "Firefox"
		},
		{
			string: navigator.vendor,
			subString: "Camino",
			identity: "Camino"
		},
		{		// for newer Netscapes (6+)
			string: navigator.userAgent,
			subString: "Netscape",
			identity: "Netscape"
		},
		{
			string: navigator.userAgent,
			subString: "MSIE",
			identity: "Explorer",
			versionSearch: "MSIE"
		},
		{
			string: navigator.userAgent,
			subString: "Gecko",
			identity: "Mozilla",
			versionSearch: "rv"
		},
		{ 		// for older Netscapes (4-)
			string: navigator.userAgent,
			subString: "Mozilla",
			identity: "Netscape",
			versionSearch: "Mozilla"
		}
	],
	dataOS : [
		{
			string: navigator.platform,
			subString: "Win",
			identity: "Windows"
		},
		{
			string: navigator.platform,
			subString: "Mac",
			identity: "Mac"
		},
		{
			string: navigator.platform,
			subString: "Linux",
			identity: "Linux"
		}
	]

};
BrowserDetect.init();

///////////////////////////////////////////////////////////////////
// ImageUpload

function ImageUpload() {
    this.focusElement = null;
}

ImageUpload.prototype.addNewImage = function(sImageId) {	
	var oTargetDiv = document.getElementById("new_images_div");
    var oHidden = document.createElement("input");
	oHidden.type = "hidden";
	oHidden.id = "new_bounty_image_" + sImageId + "_id";
	oHidden.name = "new_bounty_image[" + sImageId + "][id]";
	oHidden.value = sImageId;	
	oTargetDiv.appendChild(oHidden);
}

ImageUpload.prototype.addDeletion = function(sImageId, sDiv) {	
	var oTargetDiv = document.getElementById(sDiv);
    var oHidden = document.createElement("input");
	oHidden.type = "hidden";
	oHidden.id = "existing_image_deletion_" + sImageId + "_id";
	oHidden.name = "existing_image_deletion[" + sImageId + "][id]";
	oHidden.value = sImageId;	
	oTargetDiv.appendChild(oHidden);
}

ImageUpload.prototype.removeNewImage = function(sImageId) {	
	var oTargetDiv = document.getElementById("new_images_div");
    var oHidden = document.getElementById("new_bounty_image_" + sImageId + "_id");
	oTargetDiv.removeChild(oHidden);
}

ImageUpload.prototype.clearNewImages = function() {
	var oTargetDiv = document.getElementById("new_images_div");	
	var firstNode = oTargetDiv.firstChild;
	
	if (firstNode) {
    	var node;
    	while (node = firstNode.nextSibling) {
    	   oTargetDiv.removeChild(node);        
    	}
        oTargetDiv.removeChild(firstNode);
    }
}

ImageUpload.prototype.setActiveImage = function(oElement, sId) {
    if (oElement == this.focusElement) {
        this.imageSelected(oElement, false);
        setActiveImageValues('');
		this.enableUpload(true);      
    } else {
        this.imageSelected(oElement, true);
		setActiveImageValues(sId);
		this.enableUpload(false);
    }        
}

function setActiveImageValues(sValue) {
    var oActiveImageHidden = document.getElementById("image_active_image");
    var obountyActiveImageHidden = document.getElementById("bounty_active_image");
    oActiveImageHidden.value = sValue;
    obountyActiveImageHidden.value = sValue;	
}

ImageUpload.prototype.enableUpload = function(setting) {
    var oImagesDiv = document.getElementById("new_images_div");
	var children = oImagesDiv.childNodes;
	var oUpload = document.getElementById("image_uploaded_image");
	if (setting == true) {
		if (children.length == 6) {
			oUpload.disabled = true;
		} else {
			oUpload.disabled = false;
		}
	} else {
		oUpload.disabled = false;		
	}
}

ImageUpload.prototype.imageSelected = function(oElement, setting)  {
    var oSelDiv = oElement.parentNode.parentNode.parentNode;
    if (setting === true) {
        this._setImageHighlighting(oSelDiv, true);
        if (this.focusElement != null) {
            this._setImageHighlighting(this.focusElement.parentNode.parentNode.parentNode, false);
        }
        this.focusElement = oElement; 
		showElementInline('delete_image_button');
    } else {
        this._setImageHighlighting(oSelDiv, false);
        if (this.focusElement != null) {
            this._setImageHighlighting(this.focusElement.parentNode.parentNode.parentNode, false);
            this.focusElement = null;
        }
		hideElement('delete_image_button');
    }
}

ImageUpload.prototype.setFocusElementById = function(sElement) {	
	var oElement = document.getElementById(sElement);
	this.focusElement = oElement;	
}

ImageUpload.prototype.setEmptyImage = function(oElement) {
    var oSelDiv = oElement.parentNode.parentNode.parentNode;
    
	setActiveImageValues('');

    if (oSelDiv.className == 'small-thumb') {
        this._setImageHighlighting(oSelDiv, true);
        if (this.focusElement != null) {
            this._setImageHighlighting(this.focusElement.parentNode.parentNode.parentNode, false);            
        }        
        this.focusElement = oElement; 
    } else {
        this._setImageHighlighting(oSelDiv, false);
        this.focusElement = null;
    }        
    document.getElementById('image_preview').src = "/images/img/thumb_large.gif";
	hideElement('delete_image_button');
}

ImageUpload.prototype._setImageHighlighting = function(oElement, setting) {
    var style = 'none';
    var className = 'small-thumb';
    if (setting === true) {
        className = 'small-thumb-sel';
    } 
    oElement.className = className;
}

function confirmImageUpload() {
	isImageForUpload = document.getElementById("image_uploaded_image").value != '';
	
	if (isImageForUpload && !confirm('By clicking on OK, you certify that you have the right to distribute this image, and that it does not violate Sharedbounties Terms and Conditions')) {
		return false;
	}
	
	var oActiveImageHidden = document.getElementById("image_active_image");

	if (oActiveImageHidden.value && oActiveImageHidden.value != "") {
		var bUpload;
		if (!isImageForUpload) {
			bUpload = confirm("You are about to delete the selected image. Do you wish to proceed?");			
		} else {
			bUpload = confirm("You are about to replace an existing image. Do you wish to proceed?");
		}
		return bUpload;
	}
	
	return true;
}

function confirmVideoUpload() {
	return confirm('By clicking on OK, you certify that you have the right to distribute this video file, and that it does not violate Sharedbounties Terms and Conditions');
}


function confirmImageDelete() {
    var oActiveImageHidden = document.getElementById("image_active_image");
    if (oActiveImageHidden.value && oActiveImageHidden.value != "") {
		return confirm("Selected image will be deleted! Do you wish to proceed?");			
	}
	return false;
}

function confirmProfileImageDelete() {
	return confirm("Avatar image will be deleted! Do you wish to proceed?");			
}

function previewImage(sImage, sSrc) {
    var oImage = document.getElementById(sImage);
    var oParent = oImage.parentNode;
    var oNewImage = document.createElement("img");
    oNewImage.id = oImage.id;
    oNewImage.name = oImage.name;
    oParent.replaceChild(oNewImage, oImage);
    oNewImage.onload = function() { centerImage(oNewImage) };
    oNewImage.src = sSrc;	
}

function previewIEImage(oImage) {
	var sSrc = oImage.src;
    var oParent = oImage.parentNode;
    var oNewImage = document.createElement("img");
    oNewImage.id = oImage.id;
	oNewImage.style.visibility = "hidden";
    oNewImage.name = oImage.name;
    oParent.replaceChild(oNewImage, oImage);
    oNewImage.onload = function() { waitFor(oNewImage) };
    oNewImage.src = sSrc;	
}

function previewIEThumbImage(oImage) {
	var sSrc = oImage.src;
    var oParent = oImage.parentNode;
    var oNewImage = document.createElement("img");
    oNewImage.id = oImage.id;
	oNewImage.style.visibility = "hidden";
    oNewImage.name = oImage.name;
    oParent.replaceChild(oNewImage, oImage);
    oNewImage.onload = function() { waitForThumb(oNewImage) };
    oNewImage.src = sSrc;	
}

function centerImage(oImage, offset) {
    if (offset == null) {
		offset = 12;		
	}
    if (BrowserDetect.browser == 'Explorer') {
        offset += 2;
    }
	oImage.parentNode.style.marginTop = '-' + (oImage.height / 2 + offset) + 'px';
	oImage.style.visibility = "visible";
}

var imgWait;
function waitFor(oImage, offset) {
	if(oImage.height == 0) {
		imgWait = setTimeout(function(){waitFor(oImage, offset)}, 250);
	} else{
		clearTimeout(imgWait);
		centerImage(oImage, offset);
	}
}

function centerPbountyImage(offset, imgId) {
	if (imgId == null) {
		imgId = 'image_preview';
	}
	var oImage = document.getElementById(imgId);
	oImage.style.visibility = "hidden";
	if (oImage.height != 0) {
		centerImage(oImage, offset);
	}
	
	if (oImage.height == 0) {
		previewIEImage(oImage, offset);
	}
}

function centerThumbImage(oImage) {
    if (oImage.height == 0) {
		oImage.style.visibility = "hidden";
		previewIEThumbImage(oImage);			
	} else {
		offset = 4;
    	if (BrowserDetect.browser == 'Explorer') {
        	offset += 1;
    	}
		oImage.style.visibility = "visible";
		oImage.parentNode.parentNode.style.marginTop = '-' + (oImage.height / 2 + offset) + 'px' ;
	}
}

function waitForThumb(oImage) {
	if(oImage.height == 0) {
		imgWait = setTimeout(function(){waitForThumb(oImage)}, 250);
	} else{
		clearTimeout(imgWait);
		centerThumbImage(oImage);
	}
}

function centerThumbs() {
	var divs = document.getElementsByTagName("div");
	for (var i = 0; i < divs.length; i++) {
		if(divs[i].className.match("small-thumb-center")) {
			var oImage = divs[i].getElementsByTagName("img");
			if (oImage[0] != null) {
				centerThumbImage(oImage[0]);
			}
		}
	}
}
/////////////////////////////////////////////////////////////////////////////
// Grow text box
function resizeTextarea(oTextarea, minRows) {
	var characterCount = oTextarea.value.length;
	var columnCount = Math.floor(oTextarea.cols * 3);
	var height = oTextarea.rows;
	var newHeight = 1 + Math.floor(characterCount/columnCount);
	if (newHeight != height && newHeight >= minRows) {
		oTextarea.rows = newHeight;
	}
}

function resizeTinyTextarea(oTextarea, minRows) {
	var characterCount;
	try {
		characterCount = tinyMCE.getContent(oTextarea.id).length;
	} catch (e) {
		// no tinyMCE!
		characterCount = oTextarea.value.length;
	}	
	var columnCount = Math.floor(oTextarea.cols * 3);
	var height = oTextarea.rows;
	var newHeight = 1 + Math.floor(characterCount/columnCount);
	if (newHeight != height && newHeight >= minRows) {
		oTextarea.rows = newHeight;
		tinyMCE.triggerNodeChange();
	}
}

//////////////////////////////////////////////////////////////////////////
// Count Characters
function countChars(oTextarea, sTarget) {  
    var oTarget = document.getElementById(sTarget);
    var oTextNode = document.createTextNode(oTextarea.value.length + 1);
    var firstChild = oTarget.firstChild
    oTarget.replaceChild(oTextNode, firstChild);
    
    var color = "green";
    if (oTextarea.value.length < 750) {
        color = "#C54949";
    }
    oTarget.style['color'] = color;
}

function countTinyChars(oTextarea, sTarget) {  
    var oTarget = document.getElementById(sTarget);
	var characterCount;
	try {
		characterCount = tinyMCE.getContent(oTextarea.id).length;
	} catch (e) {
		// no tinyMCE!
		characterCount = oTextarea.value.length;
	}
	
	
    var oTextNode = document.createTextNode(characterCount + 1);
    var firstChild = oTarget.firstChild
    oTarget.replaceChild(oTextNode, firstChild);
    
    var color = "green";
    if (characterCount < 750) {
        color = "#C54949";
    }
    oTarget.style['color'] = color;
}

function triggerChangeOnTexarea() {
	var oTextarea = document.getElementById('bounty_body');
    oTextarea.value = tinyMCE.getContent(oTextarea.id);
	dispatchChangeEvent(oTextarea);	
}

function createTinyMceListener(elementName, eventName) {   
	tinyMCE.execCommand("mceAddControl", true, elementName);
	
	var theFrame = $('mce_editor_0');
	if(theFrame.contentDocument) {
	    Event.observe(theFrame.contentDocument, 'blur', triggerChangeOnTexarea);
	} else {
	    Event.observe(theFrame, 'blur', triggerChangeOnTexarea);
	}	
	tinyMCE.addEvent(tinyMCE.getInstanceById(elementName).getDoc(), eventName, bountyEntryTextAreaHandler);	
	return;
}

function bountyEntryTextAreaHandler(e) {
 var elem = document.getElementById('bounty_body');
	resizeTinyTextarea(elem, 5);
	countTinyChars(elem, 'count_info');	
}

///////////////////////////////////////////////////////////////////////
// TabMenu
function TabMenu(name) {
    this.latestMouseOver = null;
    this.oSelectedMenuTab = null;
    this.sCurrentRowCol = null;
    this.bSelectorInUse = false;
    this.lastFillerCell = null;
    this.timer = null;
    this.name = name;
    this.canClick = true;
    this.effect = null;
}

TabMenu.prototype.simulateClick = function(oElement) {  
  if (this.canClick === true && this.latestMouseOver != oElement) {
      this.latestMouseOver = oElement;
      setTimeout(function (){_simulateClick(tabMenu.latestMouseOver, oElement)}, 300);
  }
}

function _simulateClick(latestMouseOver, oElement) {
  if (latestMouseOver == oElement) {
      if (oElement.click) {
          oElement.click();
      } else {
		if( document.createEvent ) {
			var evt = document.createEvent("MouseEvents");
			evt.initMouseEvent("click", true, true, window,
			0, 0, 0, 0, 0, false, false, false, false, 0, null);
			oElement.dispatchEvent(evt);
		} else if( document.createEventObject ) {
			oElement.fireEvent('onmouseclick');
		}	  	
      }
  }
}

TabMenu.prototype.clearIntent = function(oElement) {
    if (oElement == this.latestMouseOver) {
        this.latestMouseOver = null;
    }
}

TabMenu.prototype.setCanClick = function(setting) {
    this.canClick = setting;
}

TabMenu.prototype.setSelectedMenuTab = function(sId) {
    this.oSelectedMenuTab = document.getElementById(sId);
    this.oSelectedMenuTab.style.backgroundColor = 'white';
}

TabMenu.prototype.setCurrentRowCol = function(sRowCol) {
    this.sCurrentRowCol = sRowCol;
}

TabMenu.prototype.clearSelectedMenuTab = function() {
	if (this.oSelectedMenuTab != null) {
    	var firstNode = this.oSelectedMenuTab.firstChild;
    	
    	if (firstNode) {
        	var node;
        	while (node = firstNode.nextSibling) {
        	   this.oSelectedMenuTab.removeChild(node);        
        	}
            this.oSelectedMenuTab.removeChild(firstNode);
        }    
        this.oSelectedMenuTab.style.backgroundColor = '';

        var sImgOff = "img_" + this.sCurrentRowCol + "_off";
        var oDivImg = document.getElementById(sImgOff);
        oDivImg.style.display = "block";    
        var sImgOn = "img_" + this.sCurrentRowCol + "_on";
        oDivImg = document.getElementById(sImgOn);
        oDivImg.style.display = "none";    
    }
}

TabMenu.prototype.selectorInUse = function(event) {
    if (!event) var event = window.event;
	var relTarg = event.relatedTarget || event.fromElement;
    if (relTarg && relTarg.id == "category_selection_div") {	
        if (this.bSelectorInUse === false) {
            this.bSelectorInUse = true;
        }
    }
}

TabMenu.prototype.selectorNotInUse = function(event) {
    if (!event) var event = window.event;
	var relTarg = (event.relatedTarget) ? event.relatedTarget : event.toElement;
    if (relTarg && relTarg.id == "category_selection_div") {	
        clearTimeout(this.timer);        
        this.bSelectorInUse = false;
        this.setCanClick(true);
        this.effect = null;
        this.observeSelector();
    }
}


TabMenu.prototype.checkIfSelectorInUse = function() {
    if (!this.bSelectorInUse && this.canClick) {
        this.latestMouseOver = null;
        if (this.lastFillerCell) {
            this.lastFillerCell.style.backgroundColor = '';
        }
        this.clearSelectedMenuTab();
        clearTimeout(this.timer);        
    }
}

TabMenu.prototype.observeSelector = function() {
    setTimeout(this.name + ".checkIfSelectorInUse()", 3000);
    this.timer = setTimeout(this.name + ".observeSelector()", 3000);
}

TabMenu.prototype.setFiller = function(sRowCol) {

    var sCell = "td_" + sRowCol;
    if (this.lastFillerCell) {
        this.lastFillerCell.style.backgroundColor = '';
    }
    
    var oCell = document.getElementById(sCell);
    oCell.style.backgroundColor = "white";
    this.lastFillerCell = oCell;

    var sImgOff = "img_" + sRowCol + "_off";
    var oDivImg = document.getElementById(sImgOff);
    oDivImg.style.display = "none";    
    var sImgOn = "img_" + sRowCol + "_on";
    oDivImg = document.getElementById(sImgOn);
    oDivImg.style.display = "block";    
}

TabMenu.prototype.doSlideDown = function(sCell) {
    var oCell = document.getElementById(sCell);
    //this.effect = new Effect.BlindDown(oCell, {duration: 1.5, beforeStart: callBackStart, afterFinish: callBackFinish});
}

function callBackStart(obj) {
    tabMenu.setCanClick(false);
}

function callBackFinish(obj) {
    tabMenu.setCanClick(true);
}
///


///////////////////////////////////////////////////////////////////////
// bounty entry specific
function closeCategorySelection() {
    oElement = document.getElementById('category_selection_div');
    oElement.style.diplay = "none";    
}

function setCategoryId(sId) {
    document.getElementById('bounty_category_id').value = sId;
}
///

////////////////////////////////////////////////////////////////////////////////////////
// ImageSlider 
function ImageSlider(id, targetElement, controlWidth, pointBoxWidth, spacerWidth, read_only) {
    this.id = id;
    this.read_only = read_only;
    this.targetElement = targetElement;
    this.grippy = 'slider_div_grippy_' + id;
    this.targetInitVal = '0.0';  
    this.controlWidth = controlWidth;
    this.pointBoxWidth = pointBoxWidth;
    this.spacerWidth = spacerWidth;
    this.stepWidth = pointBoxWidth / 10;
}

ImageSlider.prototype.startImageSlider = function(oElement) {
    oElementInput = document.getElementById(this.targetElement);
    this.targetInitVal = oElementInput.value; 
    oElement.onmousemove = this.wrapEvent();
}

ImageSlider.prototype.wrapEvent = function() {
    oElem = this;
    return doMove;
}

ImageSlider.prototype.stopMouseMove = function(oElement) {
    oElement.onmousemove = null;
}

ImageSlider.prototype.stopImageSlider = function(oElement) {
    this.stopMouseMove(oElement);
    oElementInput = document.getElementById(this.targetElement);
    oElementInput.value = this.targetInitVal;
    this.setPosFromValue(oElementInput.value);
}

ImageSlider.prototype.clickImageSlider = function(oElement) {        
    this.stopMouseMove(oElement); // disable selection (onmousemove) after click until next onmouseover?
    oElementInput = document.getElementById(this.targetElement);
    this.targetInitVal = oElementInput.value;
    oElementInput.focus();
	if( document.createEvent ) {
		var evt = document.createEvent("HTMLEvents");
		evt.initEvent("change", true, true);
		oElementInput.dispatchEvent(evt);		
	} else if( document.createEventObject ) {
		oElementInput.fireEvent('onchange');
	}	  	
}

function doMove(event) {
    oElementdiv = document.getElementById(oElem.grippy);
    oElementInput = document.getElementById(oElem.targetElement);
    event = event || window.event;
	var relTarg = event.relatedTarget || event.fromElement;
    var calcWidth = oElem.pointBoxWidth + oElem.spacerWidth;
    
    if (event) {
        // grab the x-y pos.s if browser supports clientX/Y
        if (document.body
            && typeof document.body.scrollLeft != 'undefined'
            && typeof event.clientX != 'undefined')
        {
            var tempX = event.clientX;
            var realPos = tempX - oElem.findStartPos(this);
            var row = parseInt(realPos / calcWidth);
            var ignoreAreaStart = row * calcWidth + 1;
            var ignoreAreaEnd = ignoreAreaStart + oElem.spacerWidth - 1;
            if ( realPos > 0 && realPos < oElem.controlWidth && !(realPos >= ignoreAreaStart && realPos <= ignoreAreaEnd) ) {
                var startBoxArea = row * calcWidth + oElem.spacerWidth;
                var decimal = parseInt((realPos - startBoxArea) / oElem.stepWidth);
                if (decimal < 0) {
                    decimal = 0;
                }
                if (decimal == 0) {
                    oElementInput.value = parseFloat(row, 10);                
                } else {
                    oElementInput.value = row + '.' + decimal;
                }
                oElementdiv.style.width = realPos + 'px';
            }
        }
    }        
}

ImageSlider.prototype.setPosFromValue = function(sValue) {
    var decValue = sValue;
	
    decValue = (decValue == null || decValue == '') ? 0 : decValue;
    var intValue = parseInt(decValue, 10);
    var decimal = Math.ceil((decValue - intValue) * 10);
    var calcWidth = this.pointBoxWidth + this.spacerWidth;

    var realPos = intValue * calcWidth + this.spacerWidth + 1;
    if (decimal > 0) {
        realPos += decimal * this.stepWidth;
    }
    oElementdiv = document.getElementById(this.grippy);

    if (realPos > this.controlWidth) {
        realPos = this.controlWidth;
    }
    oElementdiv.style.width = realPos + 'px';

    if(!this.read_only && isDefined("slider" + this.id)) {
        eval("slider" + this.id).setValue(sValue * 10);
    }    
}

ImageSlider.prototype.findStartPos = function(obj) {
	var curleft = curtop = 0;
	if (obj.offsetParent) {
		curleft = obj.offsetLeft
		while (obj = obj.offsetParent) {
			curleft += obj.offsetLeft
		}
	}
	return curleft;
}

function isDefined(variable) {
	return eval('(typeof(' + variable + ') != "undefined");');
}

///

///////////////////////////////////////////////////////////////////
// Form Submitter
function FormSubmitter(formName, targetDiv, addedFields) {
    this.formName = formName;
    this.addedFields = addedFields;
}

FormSubmitter.prototype.submitForm = function() {
    oForm = document.getElementById(this.formName);
    oTargetDiv = document.getElementById(this.targetDiv);
    this.copyFields(oTargetDiv);
	this.copyBodyField(oTargetDiv);
    oForm.submit();
    this.cleanFields(oTargetDiv);
}

FormSubmitter.prototype.copyFields = function(oTargetDiv) {

    for (var i = 0; i < this.addedFields; i++) {
        var oField = document.getElementById(this.addedFields[i]);
        var oHidden = document.createElement("input");
        oHidden.type = "hidden";
        oHidden.id = this.addedFields[i];
        oHidden.name = oField.name;
        oHidden.value = oField.value;	
        oTargetDiv.appendChild(oHidden);
    }
}

FormSubmitter.prototype.copyBodyField = function(oTargetDiv) {
    var oText = document.getElementById('bounty_body');
    oText.value = tinyMCE.getContent('bounty_body');	
}

FormSubmitter.prototype.cleanFields = function(oTargetDiv) {
	var firstNode = this.oTargetDiv.firstChild;
	
	if (firstNode) {
    	var node;
    	while (node = firstNode.nextSibling) {
    	   this.oTargetDiv.removeChild(node);        
    	}
        this.oTargetDiv.removeChild(firstNode);
    }    
}

/////////////////////////////////////////////////////////////////
// ElementEnabler
function enableElements(aElements, bSetting) {
    for (var i = 0; i < aElements.length; i++) {
        var oField = document.getElementById(aElements[i]);
        oField.disabled = bSetting;
    }    
}

function switchColors(aElements, bSetting) {
    for (var i = 0; i < aElements.length; i++) {
        var oElem = document.getElementById(aElements[i]);
        if (bSetting == true) {
			oElem.style.color = '#7AA09B';
			oElem.style.fontWeight = 'bold';
		} else {
			oElem.style.color = '#C6C6C6';
			oElem.style.fontWeight = 'normal';
		}
    }    	
}

function toggleCheckboxes(sOnElement, sOffElement) {
    var oOnElement = document.getElementById(sOnElement);
    var oOffElement = document.getElementById(sOffElement);
	
    oOnParent = oOnElement.parentNode;
    oOffParent = oOffElement.parentNode;
    
    oOnElement.checked = true;
	oOnElement.value = true;
    oOnParent.className = "checkbox selected";
    oOnParent.style.backgroundPosition = "0 -52px";

    oOffElement.checked = false;
	oOffElement.value = false;
    oOffParent.className = "checkbox";
    oOffParent.style.backgroundPosition = "0 0px";	
}

function handleValidationOwnitTriedit() {
	new Ajax.Request(
		'/bounty/validate_bounty?field=own_it', {
			asynchronous:true, 
			evalScripts:true, 
			parameters:'bounty_own_it=' + escape($('bounty_own_it').value) + '&bounty_tried_it=' + escape($('bounty_tried_it').value)
		}
	);	
}

function toggleTwins(oElem) {
	var oInput = oElem.getElementsByTagName('INPUT');
	var aElems = document.getElementsByName(oInput[0].name);
	for (var i = 0; i < aElems.length; i++) {
		if (aElems[i].type == 'checkbox' && oInput[0] != aElems[i]) {	
			aElems[i].checked = false;
			oParent = aElems[i].parentNode;
    		oParent.className = "checkbox";
    		oParent.style.backgroundPosition = "0px 0px";
		}
	}	
}

function setHidden(sTarget, oSource) {
	//debugger
	var oInput = document.getElementById(sTarget);
	var oCheckbox = oSource.getElementsByTagName('INPUT')[0];
	if (oCheckbox.checked == true) {
		oInput.value = oCheckbox.value;
	} else {
		oInput.value = '';		
	}	

	// dispatch change event to trigger validation on the field
	if( document.createEvent ) {
		var evt = document.createEvent("HTMLEvents");
		evt.initEvent("change", true, true);
		oInput.dispatchEvent(evt);		
	} else if( document.createEventObject ) {
		oInput.fireEvent('onchange');
	}	  	
}

function setHiddenRadio(sTarget, oSource) {
	//debugger
	var oInput = document.getElementById(sTarget);
	var oRadio = oSource.getElementsByTagName('INPUT')[0];
	if (oRadio.checked == true) {
		oInput.value = oRadio.value;
	} else {
		oInput.value = '';		
	}	

	// dispatch change event to trigger validation on the field
	if( document.createEvent ) {
		var evt = document.createEvent("HTMLEvents");
		evt.initEvent("change", true, true);
		oInput.dispatchEvent(evt);		
	} else if( document.createEventObject ) {
		oInput.fireEvent('onchange');
	}	  	
}

function dispatchChangeEvent(oElem) {
	//debugger
	if( document.createEvent ) {
		var evt = document.createEvent("HTMLEvents");
		evt.initEvent("change", true, true);
		oElem.dispatchEvent(evt);		
	} else if( document.createEventObject ) {
		oElem.fireEvent('onchange');
	}	  	
}

function dispatchClickEvent(oElem) {
	if( document.createEvent ) {
		var evt = document.createEvent("MouseEvents");
		evt.initMouseEvent("click", true, true, window,
		0, 0, 0, 0, 0, false, false, false, false, 0, null);
		oElem.dispatchEvent(evt);
	} else if( document.createEventObject ) {
		oElem.fireEvent('onmouseclick');
	}	  	
}

//////////////////////////////////////////////////////////
// Custom rating helpers
function showRemoveButton(oElemHide, sElemShow) {
    var oElemShow = document.getElementById(sElemShow);
    oElemShow.style.display = 'block';
    oElemHide.style.display = 'none';
}

function removeCustomRating(sElemRemove) {
    oElemRemove = document.getElementById(sElemRemove);
    oElemParent = oElemRemove.parentNode;
    oElemParent.removeChild(oElemRemove);
	
	var oHidden = document.getElementById('hidden_custom_feature');
	if (oHidden.value != null && oHidden.value != '') {
		var oHiddenDiv = document.getElementById(oHidden.value);
		if (oHiddenDiv) {
			oHiddenDiv.style.display = 'block';
			recalculateSliders();
		}
	}
}

function addSubmittable(oElem, sParameterName, sId) {
    var oHidden = document.getElementById(sParameterName + "_" + sId + "_submittable");
    oHidden.value = "true";	
}

function removeCustomFeature(sRemoveId) {	
    var oTargetDiv = document.getElementById('new_bounty_features_div');
    var oHidden = document.createElement("input");
	oHidden.type = "hidden";
	oHidden.id = "remove_custom_feature_" + sRemoveId;
	oHidden.name = "remove_custom_feature[" + sRemoveId + "]";
	oHidden.value = sRemoveId;
    oTargetDiv.appendChild(oHidden);
}

function enforceLimit(oElement, fLimit) {
    if (parseFloat(oElement.value, 10) > fLimit) {
        oElement.value = fLimit;        
    }
	var anum=/(^\d+$)|(^\d+\.\d+$)|(^\d+\.)$/;
	if (oElement.value && !anum.test(oElement.value)) {
		oElement.value = fLimit;
	}
}

function checkCustomFeaturesLimit(sDiv) {
	var oCheckDiv = document.getElementById('new_bounty_features_div');
	var oTargetDiv = document.getElementById(sDiv);
	var children = oCheckDiv.getElementsByTagName('span');
	var count = 0;	
	for (var i = 0; i < children.length; i++) {
		if (children[i].id.indexOf('bounty_feature') != -1) {
			count++;
		}
	}
	
	if (count == 7) {
		oTargetDiv.style.display = 'none';
		var oRecord = document.getElementById('hidden_custom_feature');
		oRecord.value = sDiv;
	} else {
		oTargetDiv.style.display = 'block';
	}
}

function replaceCustomLabelText(sId) {
	var oText = document.createTextNode('Your Custom Rating:');
	var oLabel = document.getElementById('title_label_' + sId);
	oLabel.replaceChild(oText, oLabel.firstChild);
}

//////////////////////////////////////////////////////////////
// Submit multiple forms
function submitForms(sPrimaryForm, aSecondaryForms) {
    var oPrimaryForm = document.getElementById(sPrimaryForm);

    oPrimaryForm.submit();
}

function submitFormsForPbounty(sPrimaryForm, aSecondaryForms) {
    var oPrimaryForm = document.getElementById(sPrimaryForm);
    var oHidden = document.createElement("input");
	oHidden.type = "hidden";
	oHidden.id = 'preview';
	oHidden.name = 'preview';
	oHidden.value = 'preview';	
	oPrimaryForm.appendChild(oHidden);                
    submitForms(sPrimaryForm, aSecondaryForms);
}

function submitFormsForDraft(sPrimaryForm, aSecondaryForms) {
    var oPrimaryForm = document.getElementById(sPrimaryForm);
    var oHidden = document.createElement("input");
	oHidden.type = "hidden";
	oHidden.id = 'draft';
	oHidden.name = 'draft';
	oHidden.value = 'draft';	
	oPrimaryForm.appendChild(oHidden);                
    submitForms(sPrimaryForm, aSecondaryForms);
}

function switchPbountyToEdit() {
    var oDivEdit = document.getElementById("bounty_entry_page_div");
    var oDivPbounty = document.getElementById("bounty_preview_page_div");
    oDivEdit.style.display = "block";
    oDivPbounty.style.display = "none";
    // have to do this to refresh the sliders, otherwise they render weird
    // after being displayed
	recalculateSliders();
	centerPbountyImage();
	centerThumbs();
}

function recalculateSliders() {
	if (oSliderArray) {
		for (var i in oSliderArray) {
           if (i.indexOf('slider') != -1) {
	           oSliderArray[i].recalculate();
	       }
        }
    }
}
///

///////////////////////////////////////////////////////////////
// Flash movie stuff
function getFlashMovie(movieName) {
  return document.getElementById(movieName);
//  var isIE = navigator.appName.indexOf("Microsoft") != -1;
//  return (isIE) ? window[movieName] : document[movieName];
}

function recordFromJS(movieName) {
    getFlashMovie(movieName).startRecording();  
}
 
function registerVideoForUse() {
	var oTargetDiv = document.getElementById("new_video_div");
	var oHidden = document.getElementById('video_capture');
	if (oHidden == null) {
	    oHidden = document.createElement("input");
		oHidden.type = "hidden";
		oHidden.id = "video_capture";
		oHidden.name = "video_capture";
	    oTargetDiv.appendChild(oHidden);
	}
	oHidden.value = '1';
	var owner = document.getElementById('owner').value;

	if (owner == "member") {
		var currId = document.getElementById('member_movie_id').value;
		new Ajax.Request('/member_account/get_delete_video_btn/?id=' + currId + '&owner=' + owner, {asynchronous:true, evalScripts:true});
	} else {
		var currId = document.getElementById('bounty_movie_id').value;
		new Ajax.Request('/bounty/get_delete_video_btn/?id=' + currId + '&owner=' + owner, {asynchronous:true, evalScripts:true});
	}
}

function resetVideoUse() {
	var oHidden = document.getElementById('video_capture');
	if (oHidden != null) {
		oHidden.value = '';
	}	
}

/////////////////////////////////////////////////////////////////////////////
// Video upload
function setVideo(sVideoId) {	
	var oTargetDiv = document.getElementById("new_video_div");
    var oHidden = document.createElement("input");
	oHidden.type = "hidden";
	oHidden.id = "bounty_movie_id";
	oHidden.name = "bounty[movie_id]";
	oHidden.value = sVideoId;
	
    var firstNode = oTargetDiv.firstChild;	
	if (firstNode) {
    	var node;
    	while (node = firstNode.nextSibling) {
    	   oTargetDiv.removeChild(node);        
    	}
        oTargetDiv.removeChild(firstNode);
    }    	
    oTargetDiv.appendChild(oHidden);
}

function removeVideo(sVideoId) {	
	var oTargetDiv = document.getElementById("new_video_div");
    var oHidden = document.getElementById("bounty_video_" + sImageId + "_id");
	oTargetDiv.removeChild(oHidden);
}

function setMemberVideo(sVideoId) {	
	var oHidden = document.getElementById("member_movie_id");
	// First time it doesn't exist as it is rendered after this call
	// and it is not important anyway as it is set to correct value
	if (oHidden) {
		oHidden.value = sVideoId;	
	}
}

////////////////////////////////////////////////////////////////////////////////
// Privacy Switch
// positions: 0 - none selected, 1 - not secure, 2 - secure
// position 0 is intial and it will not repeat itself
function PrivacySwitch(sDiv, sTarget, sInput) {
	this.oDiv = document.getElementById(sDiv);
	this.oTarget = document.getElementById(sTarget);
	this.sInput = sInput; // this element doesn't exist yet
	this.oPosition = 0;
	this.init();
}

PrivacySwitch.prototype.init = function() {
	if (this.oTarget.value == 'true') {
		this.oDiv.style.backgroundPosition = "-52px 0px";
		this.oPosition = 2;
	} else if (this.oTarget.value == 'false') {
		this.oDiv.style.backgroundPosition = "-26px 0px";
		this.oPosition = 1;
	} else {
		this.oPosition = 0;
	}
}

PrivacySwitch.prototype.rotate = function() {
	if (this.oPosition == 0) {
		this.oDiv.style.backgroundPosition = "-26px 0px";
		this.oPosition = 1;
		this.oTarget.value = 'false';
		var oInput = document.getElementById(this.sInput);
		if (oInput) {oInput.className = 'public';}
	} else if (this.oPosition == 1) {
		this.oDiv.style.backgroundPosition = "-52px 0px";
		this.oPosition = 2;
		this.oTarget.value = 'true';
		var oInput = document.getElementById(this.sInput);
		if (oInput) {oInput.className = 'private';}
	} else if (this.oPosition == 2) {
		this.oDiv.style.backgroundPosition = "-26px 0px";
		this.oPosition = 1;
		this.oTarget.value = 'false';		
		var oInput = document.getElementById(this.sInput);
		if (oInput) {oInput.className = 'public';}
	}
	// dispatch change event to trigger validation on the field
	if( document.createEvent ) {
		var evt = document.createEvent("HTMLEvents");
		evt.initEvent("change", true, true);
		this.oTarget.dispatchEvent(evt);
	} else if( document.createEventObject ) {
		this.oTarget.fireEvent('onchange');
	}
}


////////////////////////////////////////////////////////////////////////////////
// Image Pbounty
var pctMouseInside = false;
var pctOpened = false;
//function openPbounty(e, imgSrc, oRef) {
//	pctMouseInside = true;
//	setTimeout(function (){ 
//		if (pctMouseInside == true){
//			_openPbounty(e, imgSrc, oRef);
//		}
//	}, 500); 
//}
//
function openPbounty(e, imgSrc) {
  $('p-image').src = imgSrc;
  Effect.Appear('preview-image-cont', {duration: 1});
}

function closePbounty() {
  $('preview-image-cont').hide();
}

function findPos(obj) {
	var curleft = curtop = 0;
	if (obj.offsetParent) {
		curleft = obj.offsetLeft
		curtop = obj.offsetTop
		while (obj = obj.offsetParent) {
			curleft += obj.offsetLeft
			curtop += obj.offsetTop
		}
	}
	return [curleft,curtop];
}

function setHttp(sElement, sValue) {
	if (sValue.length == 0) {	
		oElement = document.getElementById(sElement);
		oElement.value = 'http://';
	}	
}

/* set temp image indicator */
function setTempImageIndicator() {
	oElement = document.getElementById("use_temp_img");
	oElement.value = 'true';
}

function setLabelOne(sValue) {
	document.getElementById('member_other_profile_one_label').value= sValue;
}

function setLabelTwo(sValue) {
	document.getElementById('member_other_profile_two_label').value= sValue;
}

/* Help Popup */
function PopupHelp(sName, sObj, sTop) {
	this.name = sName;
	this.sObj = sObj;
	this.opened = false;
	this.inHelp = false;
	this.top = sTop;
	this.timeOut;
}

PopupHelp.prototype.showHelpPopup = function() {
	if (this.opened == false) {
		var oImg = document.getElementById('help_img_' + this.name);
		var pos = findPos(oImg);
		var x = oImg.offsetLeft;
		var y = oImg.offsetTop;
	
		if (this.top == 'true') {
//			y -= (-200 - oImg.height) + 'px';
		}
		var oDiv = document.getElementById('help_popup_' + this.name);
//		oDiv.style.left = (x - 0) + 'px';
//    oDiv.style.top = (y - -450) + 'px';
    oDiv.style.width = (300) + 'px';
    oDiv.style.height = (200) + 'px';
    oDiv.style.marginTop = "-30px";
    oDiv.style.marginRight = "50px";
    oDiv.style.border = "0px";
    oDiv.style.background = "transparent";
    oDiv.style.background = "url(/images/img/help_popup.gif) 0 10px no-repeat";
		Effect.Appear(oDiv, {duration: 0});
		//oDiv.style.display = 'block';
		this.opened = true;

//      settings = {
//          tl: { radius: 20 },
//          tr: { radius: 20 },
//          bl: { radius: 20 },
//          br: { radius: 20 },
//          antiAlias: true,
//          autoPad: true,
//          validTags: ["div"]
//      }
//      var myBoxObject = new curvyCorners(settings, "help-popup");
//      myBoxObject.applyCornersToAll();
	}
}

PopupHelp.prototype.startMonitor = function() {
	this.timeOut = setTimeout(this.sObj + ".hideHelpPopupDelayed()", 0);
}

PopupHelp.prototype.markInsideHelp = function() {
	this.inHelp = true;
}

PopupHelp.prototype.markOutsideHelp = function() {
	this.inHelp = false;
}

PopupHelp.prototype.hideHelpPopupDelayed = function() {
	if (this.inHelp == false) {	
		var oDiv = document.getElementById('help_popup_' + this.name);
		Effect.Fade(oDiv, {duration: 0});
		oDiv.style.display = 'none';
		this.opened = false;
		clearTimeout(this.timeOut);
	} else {
		this.startMonitor();
	}
}

PopupHelp.prototype.hideHelpPopup = function(oDiv, e) {
	var oTarget = null;
	if (e.relatedTarget) {
		oTarget = e.relatedTarget;
	} else {
		oTarget = e.toElement;
	}
	var oChild = oDiv.getElementsByTagName("div")[0];
	
	if (oTarget && oChild && oTarget != oDiv && oChild != oDiv) {
		oDiv.style.display = 'none';
		this.inHelp = false;
		this.opened = false;
	}	
}

function toggleElement(sElement) {
	var oElement = document.getElementById(sElement);
	if (oElement.style.display == 'block') {
		oElement.style.display = 'none';
	} else {
		oElement.style.display = 'block';		
	}
}

function showElement(sElement) {
	var oElement = document.getElementById(sElement);
	oElement.style.display = 'block';
}

function showElementInline(sElement) {
	var oElement = document.getElementById(sElement);
	oElement.style.display = 'inline';
}

function hideElement(sElement) {
	var oElement = document.getElementById(sElement);
	oElement.style.display = 'none';
}

function removeElement(sId) {
	var oElement = document.getElementById(sId);
	var oParent = oElement.parentNode;
	oParent.removeChild(oElement);
}

function switchImages(oElement, sSrcOne, sSrcTwo) {
	if (oElement.src == sSrcOne) {
		oElement.src = sSrcTwo;
	} else {
		oElement.src = sSrcOne;
	}		
}

function getMousePosition(e) {
	var posx = 0;
	var posy = 0;
	if (!e) var e = window.event;
	if (e.pageX || e.pageY) 	{
		posx = e.pageX;
		posy = e.pageY;
	}
	else if (e.clientX || e.clientY) 	{
		posx = e.clientX + document.body.scrollLeft
			+ document.documentElement.scrollLeft;
		posy = e.clientY + document.body.scrollTop
			+ document.documentElement.scrollTop;
	}
	return [posx, posy];
	// posx and posy contain the mouse position relative to the document
	// Do something with this information
}
///////////////////////////////////////////////////////////////////
// Invite	

function Invite(iMaxInvites, sUpdateArea, sInputField, sInputArea, sSubmitButton) {
	this.iMaxInvites = iMaxInvites;
	this.sUpdateArea = sUpdateArea;
	this.sSubmitButton = sSubmitButton;
	this.sInputEmail = sInputField + '_email';
	this.sInputName = sInputField + '_name';
	this.sInputArea = sInputArea;
	this.iCount = 0;
	this.iRealCount = 0;
}

Invite.prototype.addInvitation = function() {
	if (this.iRealCount == this.iMaxInvites) {
		this.closeTheStore();
	} else {
		var oTargetDiv = document.getElementById(this.sUpdateArea);
		var oInputEmail = document.getElementById(this.sInputEmail);
		var oInputName = document.getElementById(this.sInputName);
		var oSubmitButton = document.getElementById(this.sSubmitButton);
		
		this.iRealCount++;		
		this.iCount++;	

		if (oInputEmail.value != null && oInputEmail.value.length > 0) {
		    var oEditInputEmail = document.createElement("input");
			oEditInputEmail.type = "text";
			oEditInputEmail.id = "invite_email_" + parseInt(this.iCount) + "_count";
			oEditInputEmail.name = "invite_email[" + parseInt(this.iCount) + "][" + parseInt(this.iCount) + "]";
			oEditInputEmail.value = oInputEmail.value;		
			oEditInputEmail.className = "input-field";
			
		    var oEditInputName = document.createElement("input");
			oEditInputName.type = "text";
			oEditInputName.id = "invite_name_" + parseInt(this.iCount) + "_count";
			oEditInputName.name = "invite_name[" + parseInt(this.iCount) + "][" + parseInt(this.iCount) + "]";
			oEditInputName.value = oInputName.value;		
			oEditInputName.className = "input-field";
			oEditInputName.maxLength = 30;
	
		    var oDiv = document.createElement("div");
			oDiv.id = "invite_email_div_" + parseInt(this.iCount);
			oDiv.className = "contain";
			var oDiv1 = document.createElement("div");
			oDiv1.className = "invite-friend-input";
			oDiv1.appendChild(oEditInputEmail);
			oDiv1.appendChild(oEditInputName);
			
			var oButton = document.createElement("a");
			oButton.onclick = function () { deleteInvitationEmail(oDiv.id) }
			var oImg = document.createElement("img");
			oButton.appendChild(oImg);
			oImg.src = "/images/img/btn_delete_friend.gif";
			oImg.alt = "Delete Friend";
			oDiv1.appendChild(oButton);			
			
			oDiv.appendChild(oDiv1);
			oTargetDiv.appendChild(oDiv);

		}
		oInputEmail.value = '';
		oInputName.value = '';
		
		if (this.iRealCount == this.iMaxInvites) {
			this.closeTheStore();		
		}
	}
}

function deleteInvitationEmail(sId) {
	var oDiv = document.getElementById(sId);
	var oParent = oDiv.parentNode;
	oParent.removeChild(oDiv);
	oInvite.iRealCount--;
	oInvite.openTheStore();
}

Invite.prototype.closeTheStore = function() {
	var oInputArea = document.getElementById(this.sInputArea);
	oInputArea.style.display = 'none';
	var oSubmitButton = document.getElementById(this.sSubmitButton);
	oSubmitButton.style.display = 'block';	
}

Invite.prototype.openTheStore = function() {
	var oInputArea = document.getElementById(this.sInputArea);
	oInputArea.style.display = 'block';
}

Invite.prototype.preview = function(sMessageInput, sTargetDiv) {
	var oMessageInput = document.getElementById(sMessageInput);	
    var oHidden = document.createElement("input");
	oHidden.type = "hidden";
	oHidden.id = "message";
	oHidden.name = "message";
	oHidden.value = oMessageInput.value
	var oTargetDiv = document.getElementById(sTargetDiv);
	oTargetDiv.appendChild(oHidden);
}

function textLimit(oElem, iMaxlen, sErrorSpan) {

	var oErrorSpan = document.getElementById(sErrorSpan);
	var len = oElem.value.length;

	if (len > iMaxlen) {
		oErrorSpan.style.display = 'block';
	} else {
		oErrorSpan.style.display = 'none';
	}

	if (len > iMaxlen) {
		oElem.value = oElem.value.substring(0, iMaxlen);
	}
}

///////////////////////////////////////////////////////////////////////
// Leaderboard
function Leaderboard(iSetNumber, iMaxSetNumber, sSetRef) {
	this.iSetNumber  = iSetNumber;
	this.iMaxSetNumber  = iMaxSetNumber;
	this.sSetRef = sSetRef;
	this.iTimeoutId = null;
	this.iExitTimeoutId = null;
	this.iCurrentSetNum = null;
	this.bAuto = true;
	this.sDirection = "right";
	this.bBusy = false;
}

Leaderboard.prototype.fadeCurrent = function() {
	clearTimeout(this.iTimeoutId);
	if (this.iCurrentSetNum != null) {
		var sCurrentSetDiv = this.sSetRef + this.iCurrentSetNum;		
		var oCurrentSetDiv = document.getElementById(sCurrentSetDiv);
		if (oCurrentSetDiv != null) {
			new Effect.Fade(sCurrentSetDiv, {duration:1});
		}
	}	
	this.move();
}

Leaderboard.prototype.move = function() {
	if (this.bAuto == true) {
		if (this.sDirection == "right") {
			this.iTimeoutId = setTimeout(function () {oLeaderboard.moveRight();}, 1000);
		} else {
			this.iTimeoutId = setTimeout(function () {oLeaderboard.moveLeft();}, 1000);		
		}
	} else {
		if (this.sDirection == "right") {
			this.iTimeoutId = setTimeout(function () {oLeaderboard.moveRight();}, 1000);
		} else {
			this.iTimeoutId = setTimeout(function () {oLeaderboard.moveLeft();}, 1000);		
		}
	}
}
	 
Leaderboard.prototype.moveSet = function() {
	var sSetDiv = this.sSetRef + this.iSetNumber;
	var oSetDiv = document.getElementById(sSetDiv);
	if (oSetDiv != null) {
		new Effect.Appear(sSetDiv, {duration:1});
	}
	this.iCurrentSetNum = this.iSetNumber;
	clearTimeout(this.iTimeoutId);
	if (this.bAuto == true) {
		oLeaderboard.iTimeoutId = setTimeout(function () {oLeaderboard.fadeCurrent();}, 4000);	
	} else {
		this.bBusy = false;
	}
}

Leaderboard.prototype.moveSetLeft = function() {
	if (this.bAuto == false) {
		if (this.bBusy == false) {
			this.bBusy = true;
			this.sDirection = "left";
			this.fadeCurrent();
		}
	} else {
		this.stopAuto();
		setTimeout(function () {oLeaderboard.moveSetLeft();}, 500);	
	}
}

Leaderboard.prototype.moveSetRight = function() {
	if (this.bAuto == false) {
		if (this.bBusy == false) {
			this.bBusy = true;
			this.sDirection = "right";
			this.fadeCurrent();
		}
	} else {
		this.stopAuto();
		setTimeout(function () {oLeaderboard.moveSetRight();}, 500);	
	}
}

Leaderboard.prototype.moveLeft = function() {
	this.moveIndexLeft();
	this.moveSet();
}

Leaderboard.prototype.moveRight = function() {
	this.moveIndexRight();
	this.moveSet();
}

Leaderboard.prototype.moveIndexLeft = function() {
	if (this.iSetNumber - 1 == 0) {
		this.iSetNumber = this.iMaxSetNumber;
	} else {
		this.iSetNumber--;	
	}
}

Leaderboard.prototype.moveIndexRight = function() {
	if (this.iSetNumber + 1 > this.iMaxSetNumber) {
		this.iSetNumber = 1;
	} else {
		this.iSetNumber++;	
	}
}

Leaderboard.prototype.stopAuto = function() {
	this.bAuto = false;	
	clearTimeout(this.iTimeoutId);
	clearTimeout(this.iExitTimeoutId);
}

Leaderboard.prototype.startAuto = function() {
	if (this.bAuto == false) {
		clearTimeout(this.iExitTimeoutId);
		this.bAuto = true;
		this.sDirection = "right";
		this.iExitTimeoutId = setTimeout(function () {oLeaderboard.fadeCurrent();}, 3000);
	}
}

function containsDOM (container, containee) {
	var isParent = false;
	do {
	if ((isParent = container == containee))
	  break;
	  containee = containee.parentNode;
	}
	while (containee != null);
	return isParent;
}

function checkMouseEnter (element, evt) {
	if (element.contains && evt.fromElement) {
	return !element.contains(evt.fromElement);
	}
	else if (evt.relatedTarget) {
	return !containsDOM(element, evt.relatedTarget);
	}
}

function checkMouseLeave (element, evt) {
	if (element.contains && evt.toElement) {
	return !element.contains(evt.toElement);
	}
	else if (evt.relatedTarget) {
	return !containsDOM(element, evt.relatedTarget);
	}
}