

function toggleDisplay(divID){
	var div = document.getElementById(divID);
	if(div == null) return;
	if(div.style.display == "none"){
		if(div._showDisplayStyle == null){
			div.style.display = "block";
		}else{
			div.style.display = div._showDisplayStyle;
		}
	}else{
		if(div._showDisplayStyle == null){
			div._showDisplayStyle = div.style.display;
		}
		div.style.display = "none";
	}
}



function GalleryController(){
    this._pendingRatingValue = null;
    this.averageRatingValue = null;
    this.aveRatingDecimalCount = 1;
}
GalleryController.prototype.initialize = function(div){
    this._div = div;
    var me = this;
    
    var ratingDiv = getFirstElementByTagNameAndClassName(div, "div", "ratingDiv");
    if(ratingDiv != null){
        // result
        this._ratingResultDiv = getFirstElementByTagNameAndClassName(div, "div", "ratingResultDiv");
        this._averageRatingSpan = getFirstElementByTagNameAndClassName(this._ratingResultDiv, "span", "aveRatingSpan");
 
        var ratingDomainKey = "";
        var ratingDomainKeyInput = getFirstElementByTagNameAndClassName(div, "input", "ratingDomainKey");
        if(ratingDomainKeyInput != null) ratingDomainKey = ratingDomainKeyInput.value;
        
        var ratingTargetType = "";
        var ratingTargetTypeInput = getFirstElementByTagNameAndClassName(div, "input", "ratingTargetType");
        if(ratingTargetTypeInput != null) ratingTargetType = ratingTargetTypeInput.value;
        
        var ratingTargetKey = "";
        var ratingTargetKeyInput = getFirstElementByTagNameAndClassName(div, "input", "ratingTargetKey");
        if(ratingTargetKeyInput != null) ratingTargetKey = ratingTargetKeyInput.value;
        
        var channelColorHex = "999999";
        var channelColorHexInput = getFirstElementByTagNameAndClassName(div, "input", "channelColorHex");
        if(channelColorHexInput != null) channelColorHex = channelColorHexInput.value;
        
        if(this._averageRatingSpan != null && this._averageRatingSpan.innerHTML != ""){
            this.averageRatingValue = parseFloat(this._averageRatingSpan.innerHTML);
        }
        // ajax controller
        this._ajaxRatingController = new AjaxRatingController();
        this._ajaxRatingController.initialize(ratingDomainKey, ratingTargetType, ratingTargetKey, function(sender, ratingStats){ me.onAjaxSuccess(sender, ratingStats); }, function(sender){ me.onAjaxFailure(sender); });
        // stars
        var starRatingDiv = getFirstElementByTagNameAndClassName(ratingDiv, "div", "starRatingDiv");
        if(starRatingDiv != null){
            this._ratingController = new StarRatingController();
            // fix the channelcolor
            this._ratingController.imageSelected = "/webapplications/betroot/images/extended/2007/colors/Star19_" + channelColorHex + "_0.gif";
            this._ratingController.imageMouseOver = "/webapplications/betroot/images/extended/2007/colors/Star19_" + channelColorHex + "_0.gif";
            this._ratingController.initialize(starRatingDiv, function(sender, ratingValue){ me.onClickRating(sender, ratingValue); });
        }
    }


    var thumbDivs = getElementsByTagNameAndClassName(div, "div", "thumbDiv");
    for(var i=0; i<thumbDivs.length; i++){
		var thumbDiv = thumbDivs[i];
		//$(thumbDiv).hover( function() { me.highlightThumb(this); }, function() { me.unHighlightThumb(this); } );
		thumbDiv.onmouseover = function() { me.highlightThumb(this); }
		thumbDiv.onmouseout = function() { me.unHighlightThumb(this); }
    }
    
}
GalleryController.prototype.onClickRating = function(sender, ratingValue){
    if(this._pendingRatingValue == ratingValue) return false;
    this._pendingRatingValue = ratingValue;
    this._ratingController.disable(); // until call comes back
    this._ratingController.setValue(this._pendingRatingValue);   // show the rating
    var sent = this._ajaxRatingController.sendRating(ratingValue);
    return sent;
}
GalleryController.prototype.onAjaxSuccess = function(sender, ratingStats){
    this._ratingController.enable(); // enable it again
    this.averageRatingValue = parseFloat(ratingStats.RatingEntryValueMean);
    this.showRatingAverage();
}
GalleryController.prototype.onAjaxFailure = function(sender){
    this._pendingRatingValue = null;
    this._ratingController.enable(); // enable it again
    this.showRatingAverage();
}
GalleryController.prototype.showRatingAverage = function(){
    if(this._ratingResultDiv == null || this._averageRatingSpan == null) return;
    this._averageRatingSpan.innerHTML = formatFloat(this.averageRatingValue, this.aveRatingDecimalCount);
    this._ratingResultDiv.style.display = "block";
}
GalleryController.prototype.highlightThumb = function(thumbDiv){
	addClass(thumbDiv, "thumbDivMouseOver");
}
GalleryController.prototype.unHighlightThumb = function(thumbDiv){
	removeClass(thumbDiv, "thumbDivMouseOver");
}


/// handles the ajax call
function AjaxRatingController(){
    this._url = "/WebApplications/betRoot/Services/generic/web/ratingservice.asmx";
    this._ratingDomainKey = null;
    this._ratingTargetType = null;
    this._ratingTargetKey = null;
    this._ratingType = "Stars";
    this._ratingUniquenessType = "NoLimit";
    this._minRatingValue = 0;
    this._maxRatingValue = 5;
    this._status = AjaxRatingControllerStatus.Setup;
    this._successCallback = null;
    this._failureCallback = null;
}
AjaxRatingController.prototype.initialize = function(ratingDomainKey, ratingTargetType, ratingTargetKey, successCallback, failureCallback){
    this._ratingDomainKey = ratingDomainKey;
    this._ratingTargetType = ratingTargetType;
    this._ratingTargetKey = ratingTargetKey;
    this._successCallback = successCallback;
    this._failureCallback = failureCallback;
    if(ratingTargetKey != null && ratingTargetKey != null && ratingTargetKey != null){
        this._status = AjaxRatingControllerStatus.FreeToRate;
    }
}
AjaxRatingController.prototype.sendRating = function(ratingValue){
    if(this._status != AjaxRatingControllerStatus.FreeToRate) return false;
    if(ratingValue < this._minRatingValue || ratingValue > this._maxRatingValue) return false;
    // don't send the same rating again
    this._status = AjaxRatingControllerStatus.SendingRating;
    this._ratingValue = ratingValue;
    var me = this;
    var pl = new SOAPClientParameters();
    pl.add("ratingDomainKey", this._ratingDomainKey);
    pl.add("ratingTargetType", this._ratingTargetType); 
    pl.add("ratingTargetKey", this._ratingTargetKey);
    pl.add("ratingType", this._ratingType);
    pl.add("ratingUniquenessType", this._ratingUniquenessType);
    pl.add("ratingValue", ratingValue);
    SOAPClient.invoke(this._url, "SetRating", pl, true, function(r, soapResponse){ me.sendRatingCallback(r, soapResponse); });
    return true;
}
AjaxRatingController.prototype.sendRatingCallback = function(ratingStats, soapResponse){
    if(ratingStats == null){
        if(this._failureCallback != null) this._failureCallback(this);
        this._status = AjaxRatingControllerStatus.FreeToRate;
    }else{
        if(this._successCallback != null) this._successCallback(this, ratingStats);
        this._status = AjaxRatingControllerStatus.FreeToRate;
    }
}

function AjaxRatingControllerStatusEnum(){
    this.Setup = 0;
    this.FreeToRate = 1;
    this.SendingRating = 2;
    this.RatingFailed = 3;
    this.RatingSucceeded = 4;
}
var AjaxRatingControllerStatus = new AjaxRatingControllerStatusEnum();


function StarRatingController(){
    this.enabled = true;
    this.value = 0;
    this.isMouseOver = false;
    this.imageNotSelected = "/webapplications/betroot/images/extended/2007/colors/Disc9-19_50_0.gif";
    this.imageSelected = "/webapplications/betroot/images/extended/2007/colors/Star19_A5A05E_0.gif";
    this.imageMouseOver = "/webapplications/betroot/images/extended/2007/colors/Star19_BE7D1F_0.gif";
    this.onClickCallback = null;
}
StarRatingController.prototype.initialize = function(div, onClickCallback){
    this._div = div;
    this.onClickCallback = onClickCallback;
    // process the anchors
    this._anchorList = getElementArrayByTagName(this._div, "a", true);
    this._starControllerList = new Array();
    var me = this;
    for(var i=0; i<this._anchorList.length; i++){
        var anchor = this._anchorList[i];
        var starController = new StarController();
        starController.initialize(this, anchor, i);
        starController.onClickCallback = function(starController){ me.onClickStar(starController); };
        starController.onMouseOverCallback = function(starController){ me.onMouseOverStar(starController); };
        starController.onMouseOutCallback = function(starController){ me.onMouseOutStar(starController); };
        this._starControllerList[this._starControllerList.length] = starController;
    }
    // set the value
    this.setValue(this.value);
}
StarRatingController.prototype.onClickStar = function(starController){
    if(!this.enabled) return;
    if(this.onClickCallback != null){
        this.onClickCallback(this, starController.value);
    }    
}
StarRatingController.prototype.onMouseOverStar = function(starController){
    if(!this.enabled) return;
    this.isMouseOver = true;
    this.setHighlights(starController.value);
}
StarRatingController.prototype.onMouseOutStar = function(starController){
    if(!this.enabled) return;
    this.delayMouseOut();
}
StarRatingController.prototype.disable = function(){
    this.enabled = false;
    this.setValue(this.value);
}
StarRatingController.prototype.enable = function(){
    this.enabled = true;
    this.setValue(this.value);
}
StarRatingController.prototype.clearHighlights = function(){
    this.setValue(this.value);
}
StarRatingController.prototype.setHighlights = function(value){
    if(value < 0 || value > 5) return;
    for(var i=0; i<value; i++){
        var starController = this._starControllerList[i];
        starController.setState(StarState.MouseOver);
    }
    for(var i=value; i<this._starControllerList.length; i++){
        var starController = this._starControllerList[i];
        starController.setState(StarState.NotSelected);
    }
}
StarRatingController.prototype.setValue = function(value){
    if(value < 0 || value > 5) return;
    this.value = value;
    for(var i=0; i<value; i++){
        var starController = this._starControllerList[i];
        starController.setState(StarState.Selected);
    }
    for(var i=value; i<this._starControllerList.length; i++){
        var starController = this._starControllerList[i];
        starController.setState(StarState.NotSelected);
    }
}
StarRatingController.prototype.delayMouseOut = function(){
    var me = this;
    this.isMouseOver = false;
    document.pageTimer.scheduleCall(function(){ me.mouseOutNow(); }, 100);
}
StarRatingController.prototype.mouseOutNow = function(){
    if(this.isMouseOver) return;
    this.clearHighlights();
}



function StarController(){
    this._state = StarState.Standard;
    this.onClickCallback = null;
    this.onMouseOverCallback = null;
    this.onMouseOutCallback = null;
    this.parent = null;
}
StarController.prototype.initialize = function(parent, anchor, index){
    this.parent = parent;
    this._anchor = anchor;
    this._index = index;
    this._image = getFirstElementByTagName(anchor, "img", true);
    this._anchor.href = "#";
    this.value = index + 1;
    var me = this;
    this._anchor.onclick = function(){ me.onClick(); };
    this._anchor.onmouseover = function(){ me.onMouseOver(); };
    this._anchor.onmouseout = function(){ me.onMouseOut(); };
}
StarController.prototype.onMouseOver = function(){
    if(this.onMouseOverCallback != null) this.onMouseOverCallback(this);
}
StarController.prototype.onMouseOut = function(){
    if(this.onMouseOutCallback != null) this.onMouseOutCallback(this);
}
StarController.prototype.onClick = function(){
    if(this.onClickCallback != null) this.onClickCallback(this);
    return false;
}
StarController.prototype.setState = function(starState){
    if(starState == StarState.NotSelected){
        this._image.src = this.parent.imageNotSelected;
    }else if(starState == StarState.Selected){
        this._image.src = this.parent.imageSelected;
    }else if(starState == StarState.MouseOver){
        this._image.src = this.parent.imageMouseOver;
    }
}




// StarState Enum
function StarStateEnum(){
    this.NotSelected = 1;
    this.Selected = 2;
    this.MouseOver = 3;
}
StarState = new StarStateEnum();




function PageTimer(){
    this.calls = new Array();
    this._keyGen = -1;
}
PageTimer.prototype.scheduleCall = function(func, msec, key){
    if(key == null) key = ++this._keyGen + "call";
    var call = this.setCall(key, func, msec);
    call.timeout = setTimeout("document.pageTimer.executeCall('" + key + "');", msec, "javascript");
}
PageTimer.prototype.executeCall = function(key){
    var call = this.calls[key];
    if(call == null) return;
    if(call.timeout != null) clearTimeout(call.timeout);
    this.calls[key] = null;
    call.func();
}
PageTimer.prototype.setCall = function(key, func, msec){
    var call = this.calls[key];
    if(call != null){
        // cancel the old call
        if(call.timeout != null) clearTimeout(call.timeout);
    }
    // create new
    call = new PageTimerCall(key, func, msec);
    this.calls[key] = call;
    return call;
}
function PageTimerCall(key, func, msec){
    this.key = key;
    this.func = func;
    this.delay = msec;
    this.timeout = null;
}

// add it to the document as a singleton
if(document.pageTimer == null) document.pageTimer = new PageTimer();





// ENTRY POINT
function setupGalleries(){
    var galleryDivList = getElementsByTagNameAndClassName(document, "div", "galleryPlayer");
    for(var i=0; i<galleryDivList.length; i++){
        var galleryDiv = galleryDivList[i];
        var galleryController = new GalleryController();
        galleryController.initialize(galleryDiv);    
    }
}
addLoadEvent(setupGalleries);



// From Common
// todo, find a better place for this

function getElementsByTagNameAndClassNames(tagName, classNames){
    if(!document.getElementsByTagName) return null;
    tagName = tagName.toUpperCase();
    var classNameList = classNames.split(",");
    var classNameLookup = new Array();
    for(var i=0; i<classNameList.length; i++){
        var className = classNameList[i];
        className = trim(className);
        if(className!= ""){
            classNameLookup[className] = true;
        }
    }
    classNames = "," + classNames + ",";
    var tags = document.getElementsByTagName(tagName);
    var list = new Array();
    for(var i=0; i<tags.length; i++){
        var tag = tags[i];
        if(tag.className == null) continue;
        if(classNameLookup[tag.className]){
            list[list.length] = tag;
        }
    }
    return list;
}

function trim(value){
	return value.replace(/^\s+|\s+$/g, '');
}

function getTextElements(rootElement){
    // create lookup to specify the tagNames to look for
    var tagNameLookup = new Array();
    tagNameLookup["A"] = true;
    tagNameLookup["SPAN"] = true;
    tagNameLookup["H1"] = true;
    tagNameLookup["H2"] = true;
    tagNameLookup["H3"] = true;
    tagNameLookup["P"] = true;
    return getElementArrayByTagNames(rootElement, tagNameLookup, true);
}
function getElementArrayByTagName(rootElement, tagName, recursive){
    var tagNameLookup = new Array();
    tagName = tagName.toUpperCase();
    tagNameLookup[tagName] = true;
    return getElementArrayByTagNames(rootElement, tagNameLookup, recursive);
}
function getElementArrayByTagNames(rootElement, tagNameLookup, recursive){
    var list = new Array();
    if(rootElement.childNodes != null){
        for(var i=0; i<rootElement.childNodes.length; i++){
            appendElementsByTagNames(rootElement.childNodes[i], tagNameLookup, recursive, list);
        }
    }
    return list;
}
function appendElementsByTagNames(currentElement, tagNameLookup, recursive, list){
    if(tagNameLookup[currentElement.tagName]) list[list.length] = currentElement;
    if(recursive){
        if(currentElement.childNodes != null){
            for(var i=0; i<currentElement.childNodes.length; i++){
                appendElementsByTagNames(currentElement.childNodes[i], tagNameLookup, recursive, list);
            }
        }
    }
}
function getFirstElementByTagName(rootElement, tagName, recursive){
    var list = getElementArrayByTagName(rootElement, tagName, recursive);
    if(list == null || list.length == 0) return null;
    return list[0];
}


function getFirstElementByTagNameAndClassName(rootElement, tagName, className, checkRoot){
    if(rootElement == null) return null;
    if(checkRoot && rootElement.tagName != null && rootElement.tagName.toUpperCase() == tagName.toUpperCase() && hasClass(rootElement, className)) return rootElement;
    // recurse
    if(rootElement.childNodes == null) return null;
    for(var i=0; i<rootElement.childNodes.length; i++){
        
        var foundElement = getFirstElementByTagNameAndClassName(rootElement.childNodes[i], tagName, className, true);
        if(foundElement != null) return foundElement;
    }
    return null;
}
function getElementsByTagNameAndClassName(rootElement, tagName, className, checkRoot, recurseOnMatch){
	if(checkRoot == null) checkRoot = false;
	if(recurseOnMatch == null) recurseOnMatch = false;
	var returnList = new Array();
	appendElementsByTagNameAndClassName(rootElement, tagName, className, checkRoot, recurseOnMatch, returnList);
	return returnList;
}
function appendElementsByTagNameAndClassName(rootElement, tagName, className, checkRoot, recurseOnMatch, returnList){
    if(rootElement == null) return;
    if(checkRoot && rootElement.tagName != null && rootElement.tagName.toUpperCase() == tagName.toUpperCase() && hasClass(rootElement, className)){
		returnList.push(rootElement);
		if(!recurseOnMatch) return;
    }
    // recurse
    if(rootElement.childNodes != null){
		for(var i=0; i<rootElement.childNodes.length; i++){
			appendElementsByTagNameAndClassName(rootElement.childNodes[i], tagName, className, true, recurseOnMatch, returnList);
		}
    }
}
function hasClass(element, className){
    checkClassNameListSetup(element);
    return (element._classNameLookup[className] == true);
}

function checkTextElementList(element){
    // if needed, creates a list for storing all text elements (recursive) within an element.
    if(element._textElementList != null) return;
    element._textElementList = getTextElements(element);
}


function addClass(element, className){
    if(hasClass(element, className)) return;
    var lastIndex = element._classNameList.length - 1;
    if(lastIndex > -1 && element._classNameList[lastIndex] == className) return;
    element._classNameList[element._classNameList.length] = className;
    element._classNameLookup[className] = true;
    var newClassName = element._classNameList[0];
    for(var i=1; i<element._classNameList.length; i++){
        newClassName += " " + element._classNameList[i];
    }
    element.className = newClassName;
}
function removeClass(element, className){
    if(!hasClass(element, className)) return;
    var newClassName = "";
    for(var i=0; i<element._classNameList.length; i++){
        if(element._classNameList[i] == className){
            element._classNameList.splice(i, 1);
        }
    }
    element._classNameLookup[className] = null;
    var newClassName = element._classNameList[0];
    for(var i=1; i<element._classNameList.length; i++){
        newClassName += " " + element._classNameList[i];
    }
    element.className = newClassName;
}

function checkClassNameListSetup(element){
    if(element._classNameList) return;
    var classNameList;
    if(element.className){
        classNameList = element.className.split(" ");
    }else{
        classNameList = new Array();
    }
    element._classNameList = classNameList;
    element._classNameLookup = new Array();
    for(var i=0; i<element._classNameList.length; i++){
        element._classNameLookup[element._classNameList[i]] = true;
    }
}

function setOnClickFromFirstHref(element){
    // add onclick to make the whole div act like an anchor tag.
    // copy the href from the first anchor tag within the div
    var anchors = getElementArrayByTagName(element, "A", true);
    if(anchors != null && anchors.length > 0){
        var firtAnchor = anchors[0];
        var href = firtAnchor.href;
        var isJavaScript = false;
        var javaScriptText;
        if(href.length > 11){
            if(href.toLowerCase().substring(0, 11) == "javascript:"){
                isJavaScript = true;
                javaScriptText = href.substring(11);
            }
        }
        if(isJavaScript){
            // fix the javascript
            eval("element.onclick = function(e){ " + javaScriptText + "; }");
            if(element.onclick){
                // disable the anchor to prevent bubbling
                firtAnchor.href = "javascript:void(null);";
            }
        }else{
            element.onclick = function(){ document.location = href; }
        }
    }
}

function formatFloat(value, decimals){
    if(decimals == null) decimals = 1;
    value = parseFloat(value);
    var mult = Math.pow(10, decimals);
    value = Math.round(value * mult) / mult;
    var result = value.toString();
    if(result.indexOf(".") == -1) result += ".";
    var zeroCount = decimals - result.length + result.indexOf(".") + 1;
    for(var i=0; i<zeroCount; i++){
        result += "0";
    }
    return result;
}






