// Add site spesific javascript here
var debugwin;
var debugwinopened = false;
function debug(str) {
    //return;
    // alert(str); return ;
    if (debugwinopened == false || !debugwin) {
        debugwin = window.open('about:blank','debug_window','width=1000,height=700, toolbars=no,menu=no,scrollbars=yes');
        debugwin.document.write("<h3>CorePublish Javascript Debug</h3>");
        debugwinopened = true;
    }
    debugwin.document.write( str );
    debugwin.focus();
    // make the debug win go away after a while..
    setTimeout("self.focus()",2000);
    // alert(str);
}

/**
*   Function displays the metods and properties of an javascript object
*   @param Object inarray - The array to serialize.
*/
function jsdebug(inarray, level) {
    var result = '';
    var sep = '';

    if (typeof level == "undefined") {
        level = 1;
    }

    if (level > 2) {
        return;
    }

    if(inarray!=null) {
        for(var key in inarray) {

            try {
                if (inarray[key] == null) {
                    continue;
                }
            } catch (e) {
                debug("<ul> Cannot debug element key [" +  key + "]</ul>");
                continue;
            }

            result = "<ul> " +  typeof inarray[key];
            result += ' [' + key + '] => ';

            try {
                tmp = inarray[key].toString();
                result += tmp.substring(0,90) + "";
            } catch (e) {
                result += tmp + "";
            }

            debug(result);

            if (typeof inarray[key] == "object" || typeof inarray[key] == "function") {
                jsdebug(inarray[key],level+1);
            }

            debug("</ul>");
            /*
            if(typeof inarray[key] == 'object') {
            result += '[object]';
            } else {
            result += inarray[key].toString();
            }     */

            /*if (result.length > 1000) {
            alert(result + " (continues >>) ");
            result = "";
            } */

        }
    } else {
        result = "[null]";
    }
    //alert(result);
}

var makeVisibleActiveIndex;
var slideTime;
var timeoutTime;

function makeVisible(link, activeIndex, numOfRows) {
	if(link.parentNode.className.match('active')) {
		return;
	};

	makeVisibleActiveIndex = activeIndex;
	slideTime = numOfRows * 0.125;
	timeoutTime = (slideTime + 0.1) * 1000;
	
	//first remove all classnames (thereby removing the "active" from current active tab)...
	$$('.xmltabs li').each(function (li) {
		li.className = "";
		});
		//...then make the clicked tab <li> active (the relevant <li> is always the parent of our "link" parameter) 
	link.parentNode.className = "active";
	
	$$('td.average').each(function(cell) {cell.style.backgroundColor = "#35b3e4"});
	
	$$('div.xml-table').each(function (element) {
		if(link.id.startsWith(element.id)) {
			
			new Effect.SlideDown(element, {queue: 'front', duration: slideTime});

			setTimeout(function() {
				$$('tr.odd td.average-'+ activeIndex).each(function (cell) {
					new Effect.Morph(cell, {style: 'background-color: #e9ebdf;'});
					});
					}, timeoutTime);
			setTimeout(function() {
				$$('tr.even td.average-'+ activeIndex).each(function (cell) {
					new Effect.Morph(cell, {style: 'background-color: #ffffff;'});
					});
					}, timeoutTime);
		} else {
			element.hide();
		}
	});
}

function setTickerHeight() {
	//document.observe("dom:loaded", function(event) {
		
		var tables = $$('div.xml-table');
		var largestSoFar = 0;
		
		tables.each(function (t) {
			currentHeight = Element.getHeight(t);
			//console.log(currentHeight);
			if(currentHeight > largestSoFar) {
				largestSoFar = currentHeight;
			}
		});
		
		var totalHeight = largestSoFar + 50;
		var grid = $('xmlgridunik');
		//console.log(grid);
		grid.setStyle({height: totalHeight + 'px'});
		
	//});
}



var refreshXMLObj; 

function refreshXml() {

	// var currentActiveTab = 

    refreshXMLObj = new CtXMLHttpRequest();
    refreshXMLObj.SetOnreadystatechange(refreshXmlCallback);
    var parameters = new Object();
    parameters["currentactivetab"] = makeVisibleActiveIndex; 
   
    refreshXMLObj.openCorePublishService("/xmlhttprequest.php" ,'imarex.refreshxml' , 'text', parameters );
}

function refreshXmlCallback() {
        if (refreshXMLObj.getReadyState() == 4) {
        	var html = refreshXMLObj.getResponseText();
        	
        	if (html.length > 0 ) {
	        	var gridDiv = document.getElementById("xmlgridunik");
	        	gridDiv.innerHTML = html;
	        	$$('td.average').each(function (cell) {
	        		new Effect.Highlight(cell, {startcolor: '#35b3e4', endcolor: '#e9ebdf'});
	        	});
	        setTickerHeight();	
        	}
        }
}

function toggleExpandCollapse(element, catID) {
	var ul = $(element).up('table').next();
	
	var expand = 0;
	
	if ((ul.style.display == '' && element.className.match('collapsed')) || ul.style.display == 'none') {
		ul.style.display = 'block';
		element.className = element.className.replace('collapsed', 'expanded');
		expand = 1;
	}
	
	
	else if((ul.style.display == '' && element.className.match('expanded')) || ul.style.display == 'block') {
		ul.style.display = 'none';
		element.className = element.className.replace('expanded', 'collapsed');
	}	
	
	var url = "/xmlhttprequest.php?service=imarex.menu.state&expand="+expand+"&categoryId="+catID;
	
	new Ajax.Request(url, {
	method: 'get' 
		/*parameters: {'service': 'imarex.menu.state',
					 'responseformat': 'header',					 
					 'expand': expand,
		             'categoryId': catID}*/
	});
	
}

/* The following override method is called for each page rendering and forces the 
attribute "align" on all image elements in article displays to be "left" */

function articleImageOverride (event) {
    var articleImages = $$('.full-articledisplay img');
    articleImages.each(function (image) {
    	var alignAttribute = image.readAttribute("align");
    	if(alignAttribute == "right") {
    		image.writeAttribute("align", "left");
    	}
    });
}

/* ...and we call it here: */

document.observe('dom:loaded', articleImageOverride);