//url, window: 'same', 'popup' or 'window'
function openDivLink(url, windowOrPopup, parameters){
	//work around double-window on a href click in a clickable div
	var nodeName = "invalidTag";
	document.onclick=function(e){
		e=e?e:event;var s,g=e.target;g=g?g:e.srcElement;
		nodeName = g.parentNode.tagName.toLowerCase();
		doWindowAction(url, windowOrPopup, nodeName, parameters);
		//remove event listener
		document.onclick = null;
	}
}

function doWindowAction(url, windowOrPopup, nodeName, parameters, height, width, positionFromTop, positionFromLeft){
	if (nodeName != "a" && nodeName != "invalidTag"){
	var fromTop = 240;//eval((screen.availHeight/2)-(height/2));
	var fromLeft = 340;//eval((screen.availWidth/2)-(width/2));
		switch (windowOrPopup) {
			case 'same': { 
				window.location.href = url;
				break 
			}
			case 'popup': {
				if (parameters.indexOf('status') == -1){
					parameters = parameters + ",status=no";
				}
				if (parameters.indexOf('height') == -1){
					parameters = parameters + ",height=" + height;
				}
				if (parameters.indexOf('width') == -1){
					parameters = parameters + ",width=" + width;
				}
				var popupWindow = window.open(url, nodeName, parameters, fromTop, fromLeft); //parameters
				popupWindow.moveTo(fromTop,fromLeft);
				break 
			}
			case 'window': { 
				window.open(url, nodeName);
				break 
			}
			default: {
				window.open(url);
				break
			}
		}
	}
}


function applyHighlighting(element, setHighlight){
	if (setHighlight){
		if (element.className.indexOf('highlight') == -1 && element.className){
				element.className = element.className + ' highlight';
		} else if (element.className.indexOf('highlight') == -1) {
			element.className = 'highlight';
		}
		if (element.type == "checkbox" || element.type == "radio"){
			try{
				checkboxElement = document.getElementById(element.name+'Lable');
				if (checkboxElement.className.indexOf('highlight') == -1 && checkboxElement.className){
					checkboxElement.className = checkboxElement.className + ' highlight';
				} else if (checkboxElement.className.indexOf('highlight') == -1) {
					checkboxElement.className = 'highlight';
				}
			} catch(e){}
		}
	} else{
		try{
			element.className = element.className.replace('highlight', '');
			if (element.type == "checkbox" || element.type == "radio"){
				checkboxElement = document.getElementById(element.name+'Lable');
				checkboxElement.className = checkboxElement.className.replace('highlight', '');
			}
		} catch(e){}
	}
}

/* for backwards compatibility - USE quickFindSelect(this)  INSTEAD */
function JumpToOtherMovie(){
	if (document.channels.mainchannels.selectedIndex != 0)
		window.location.href = document.channels.mainchannels.options[document.channels.mainchannels.selectedIndex].value;
}

function quickFindSelect(selectElement){
	if (selectElement.selectedIndex != 0)
	doWindowAction(selectElement.options[selectElement.selectedIndex].value, 'same');
}

function setHomepage(url, title){
	if (title == null || title.length == 0 ) title = document.title;
	if (url == null || url.length == 0) url = window.location.href;
	
	var navUAlowercase = navigator.userAgent;
	navUAlowercase = navUAlowercase.toLowerCase();
	if(navUAlowercase.indexOf('msie') > -1){
		//window.external.AddFavorite(url, title); //add to favourites
		event.srcElement.style.behavior='url(#default#homepage)';
		event.srcElement.setHomePage(url);
	} else {
		alert("Your browser does not allow automatic setting \nof its homepage, please set it manually.");
	}
}

/* addEvent(document.getElementById('tabBoxWrapper'), 'mouseover', stopRotating); */
function addEvent( obj, type, fn ) {
  if ( obj.attachEvent ) {
    obj['e'+type+fn] = fn;
    obj[type+fn] = function(){obj['e'+type+fn]( window.event );}
    obj.attachEvent( 'on'+type, obj[type+fn] );
  } else
    obj.addEventListener( type, fn, false );
}

/* addEvent(document.getElementById('tabBoxWrapper'), 'mouseout', restartRotating); */
function removeEvent( obj, type, fn ) {
  if ( obj.detachEvent ) {
    obj.detachEvent( 'on'+type, obj[type+fn] );
    obj[type+fn] = null;
  } else
    obj.removeEventListener( type, fn, false );
}


function setOpacity(obj, opacity) {
  opacity = (opacity == 100)?99.999:opacity;
  
  // IE/Win
  obj.style.filter = "alpha(opacity:"+opacity+")";
  
  // Safari<1.2, Konqueror
  obj.style.KHTMLOpacity = opacity/100;
  
  // Older Mozilla and Firefox
  obj.style.MozOpacity = opacity/100;
  
  // Safari 1.2, newer Firefox and Mozilla, CSS3
  obj.style.opacity = opacity/100;
}

function fadeIn(objId,opacity) {
  if (document.getElementById) {
    obj = objId; //document.getElementById(objId);
    if (opacity <= 100) {
      setOpacity(obj, opacity);
      opacity += 5;
      window.setTimeout("fadeIn('"+objId+"',"+opacity+")", 100);
    }
  }
}

function fadeOut(objId,opacity) {
  if (document.getElementById) {
    obj = objId; //document.getElementById(objId);
    if (opacity >= 0) {
      setOpacity(obj, opacity);
      opacity -= 5;
      window.setTimeout("fadeOut('"+objId+"',"+opacity+")", 100);
    }
  }
}

function setTooltip(element, tip){
	try{
		element.setAttribute('title', tip);
	} catch(e){}
}

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 scrollToObject(object, horizontalAdjustment, verticalAdjustment){
	horizontalAdjustment = horizontalAdjustment?horizontalAdjustment:0;
	verticalAdjustment = verticalAdjustment?verticalAdjustment:0;
	try{
		horizontalPosition = eval(findPos(object)[0] + horizontalAdjustment);
		verticalPosition = eval(findPos(object)[1] + verticalAdjustment);
		window.scrollTo(horizontalPosition, verticalPosition);
	} catch(e){}
}

function isInArray(needle, haystack){
    for (var i = 0; i < haystack.length; i++) {
        if (haystack[i] == needle) {
            return true;
        }
    }
    return false;
}

function includeScriptInDom(scriptFilename, parentElement, tagIndex){
	tagIndex = tagIndex ? tagIndex : 0;
    var js = document.createElement('script');
    js.setAttribute('language', 'javascript');
    js.setAttribute('type', 'text/javascript');
    js.setAttribute('src', scriptFilename);
    try{
		 //add using ID
		 parentElement.appendChild(js);
	} catch(e){
		//ID not found, add using tag name instead, tag index (if there are several tags of the same type, tagIndex defines which tag to add to.
		document.getElementsByTagName(parentElement).item(tagIndex).appendChild(js);
	}
    return false;
}

function setSidebarSectionHighlight(sectionName){
	try{
		document.getElementById(sectionName).className = 'highlight';
	} catch(e) {}
}

/* where two submit buttons are present, use this function to define which is the submit */
function submitFormOnEnter(event, form, submitButton){
	if ((event.which && event.which == 13) || (event.keyCode && event.keyCode == 13)) {
		try{
			submitButton.click();
		} catch(e){}
		return false;
	}
}


/* useful functions
http://www.javascriptsearch.com/guides/Advanced/articles/top10JSfunctionsDiaz.html */
function getElementsByClass(searchClass,node,tag) {
	var classElements = new Array();
	if ( node == null )
		node = document;
	if ( tag == null )
		tag = '*';
	var els = node.getElementsByTagName(tag);
	var elsLen = els.length;
	var pattern = new RegExp("(^|\\s)"+searchClass+"(\\s|$)"); /* CMTBC - fix \s for multiple class handling */
	for (i = 0, j = 0; i < elsLen; i++) {
		if ( pattern.test(els[i].className) ) {
			classElements[j] = els[i];
			j++;
		}
	}
	return classElements;
}

function outputAdCode(code){
	try{
		document.writeln(code);
	} catch(e){}
}

function fixUpAdCode(code){
	//fix brackets being encoded
	code = code.replace(/ipt&gt;/gi, "ipt>");
	code = code.replace(/&ltscr;/gi, "<scr");
	return code;
}


function getElementHeight(elem){
	var elem = document.getElementById(elem);
	if (elem.offsetHeight){
		return elem.offsetHeight;
	} else {
		return elem.style.pixelHeight;
	}
}

function getElementWidth(elem) {
	var elem = document.getElementById(elem);
	if (elem.offsetWidth){
		return elem.offsetWidth;
	} else {
		return elem.style.pixelWidth;
	}
}





function fixIEImageFlicker(){
	try {
		var isIE  = (navigator.appVersion.indexOf("MSIE") != -1) ? true : false;
		if (isIE) document.execCommand("BackgroundImageCache", false, true);
	} catch(err){}
}
addEvent(window, "load", fixIEImageFlicker);


/* Confirm before leaving page (eg crossword), doesn't handle form submissions yet */
/* http://drupal.org/files/issues/formcheck_8.js */
var message = "Any information you have entered will be cleared."; 
function confirmLeavePage(e){ 
	if (!e && window.event){
		e = window.event;
	}

	//var isChanged = formcheckIsFormChanged();
	
	// Don't run if submit button was clicked or form hasn't changed or there is no event
	//if (!formcheckIsSubmit && isChanged && e){
	if (e){
		e.returnValue = message;
		return message;
	}
}



function $() {
	var elements = new Array();
	for (var i=0;i<arguments.length;i++) {
		var element = arguments[i];
		if (typeof element == 'string') element = document.getElementById(element);
		if (arguments.length == 1) return element;
		elements.push(element);
	}
	return elements;
}

var BoxHeights = {
	maxh: 0,
	boxes: Array(),
	num: 0,
	op_test: false,
	equalise: function() {
		this.num = arguments.length;
		for (var i=0;i<this.num;i++) if (!$(arguments[i])) return;
		this.boxes = arguments;
		this.maxheight();
		for (var i=0;i<this.num;i++) $(arguments[i]).style.height = this.maxh+"px";
	},
	maxheight: function() {
		var heights = new Array();
		for (var i=0;i<this.num;i++) {
			if (navigator.userAgent.toLowerCase().indexOf('opera') == -1) {
				heights.push($(this.boxes[i]).scrollHeight);
			} else {
				heights.push($(this.boxes[i]).offsetHeight);
			}
		}
		heights.sort(this.sortNumeric);
		this.maxh = heights[this.num-1];
	},
	sortNumeric: function(f,s) {
		return f-s;
	}
}

var BoxInnerElementHeights = {
	maxh: 0,
	boxes: Array(),
	num: 0,
	op_test: false,
	equalise: function() {
		this.num = arguments.length;
		for (var j=0;j<this.num;j++)// if (!$(arguments[i])) return;
			this.boxes = $(arguments[j].split('>')[0]).getElementsByTagName(arguments[0].split('>')[1]);
		this.boxesNum = this.boxes.length;
		this.maxheight();
		for (var i=0;i<this.boxesNum;i++){
			$(arguments[0].split('>')[0]).getElementsByTagName(arguments[0].split('>')[1])[i].style.height = this.maxh+"px";
		}
	},
	maxheight: function() {
		var heights = new Array();
		for (var i=0;i<this.num;i++) {
			if (navigator.userAgent.toLowerCase().indexOf('opera') == -1) {
				heights.push($(this.boxes[i]).scrollHeight);
			} else {
				heights.push($(this.boxes[i]).offsetHeight);
			}
		}
		heights.sort(this.sortNumeric);
		this.maxh = heights[this.num-1];
	},
	sortNumeric: function(f,s) {
		return f-s;
	}
}
/* CMTBC - END div height normaliser */



function productwin(URL) {
day = new Date();
id = day.getTime();
eval("page" + id + " = window.open(URL, '" + id + "', 'toolbar=0,scrollbars=1,location=0,statusbar=0,menubar=0,resizable=1,width=600,height=600,left = 200,top = 100');");
}
// End -->

function popUp(URL) {
day = new Date();
id = day.getTime();
eval("page" + id + " = window.open(URL, '" + id + "', 'toolbar=0,scrollbars=1,location=0,statusbar=0,menubar=0,resizable=1,width=500,height=400,left = 200,top = 100');");
}

function productwin2(URL) {
day = new Date();
id = day.getTime();
eval("page" + id + " = window.open(URL, '" + id + "', 'toolbar=0,scrollbars=1,location=1,statusbar=0,menubar=0,resizable=1,width=800,height=700,left = 100,top = 100');");
}
