/*
Created By: Chris Campbell
Website: http://particletree.com
Date: 2/1/2006

Inspired by the lightbox implementation found at http://www.huddletogether.com/projects/lightbox/
Modified for use with DinSide.no, Digi.no etc. by Aller Internett.
Scrollable version, all browsers.
*/

/*-------------------------------GLOBAL VARIABLES------------------------------------*/

var detect = navigator.userAgent.toLowerCase();
var path = window.location.href;
var host = window.location.hostname;
var OS,browser,version,total,thestring;
var LBisActive = false;


/*-----------------------------------------------------------------------------------------------*/

// SETUP 

document.observe("dom:loaded", getBrowserInfo);
//document.observe("dom:loaded", initialize_lightboxVideo);
//Event.observe(window, "load", getBrowserInfo, false);
Event.observe(window, "load", initialize_lightboxVideo, false);

// OK: 
//document.observe("dom:loaded", asdfasdf, false);
//function asdfasdf() {alert('afd')}

Event.observe(window, 'keypress', onMyTextKeypress);

/*-----------------------------------------------------------------------------------------------*/

//Browser detect script origionally created by Peter Paul Koch at http://www.quirksmode.org/

function getBrowserInfo() {
	if (checkIt('konqueror')) {
		browser = "Konqueror";
		OS = "Linux";
	}
	else if (checkIt('safari')) browser 	= "Safari"
	else if (checkIt('omniweb')) browser 	= "OmniWeb"
	else if (checkIt('opera')) browser 		= "Opera"
	else if (checkIt('webtv')) browser 		= "WebTV";
	else if (checkIt('icab')) browser 		= "iCab"
	else if (checkIt('msie')) browser 		= "Internet Explorer"
	else if (checkIt('gecko')) browser 		= "Gecko"
	else if (!checkIt('compatible')) {
		browser = "Netscape Navigator"
		version = detect.charAt(8);
	}
	else browser = "An unknown browser";

	if (!version) version = detect.charAt(place + thestring.length);

	if (!OS) {
		if (checkIt('linux')) OS 		= "Linux";
		else if (checkIt('x11')) OS 	= "Unix";
		else if (checkIt('mac')) OS 	= "Mac"
		else if (checkIt('win')) OS 	= "Windows"
		else OS 								= "an unknown operating system";
	}
}

function checkIt(string) {
	place = detect.indexOf(string) + 1;
	thestring = string;
	return place;
}

/*-----------------------------------------------------------------------------------------------*/

//Event.observe(window, 'load', initialize_lightboxVideo, false);
//Event.observe(window, 'load', getBrowserInfo, false);
//document.observe("dom:loaded", initialize_lightboxVideo);


var lightboxVideo = Class.create();

lightboxVideo.prototype = {

	yPos : 0,
	xPos : 0,

	initialize: function(ctrl) {
		this.content = ctrl.href;
		
		Event.observe(ctrl, 'click', this.activate.bindAsEventListener(this), false);
		ctrl.onclick = function(){return false;};
		
        // Check if video shall be activated immediately
        this.directLoad();
	
	},
	
	// Activate on load if url-match, directLoadId is set before script is included. isActive is used to avoid multiple loads if the same album is linked several times in the article.
	directLoad: function() {
		directLoadId = getKey('videoid');
		try {
            if (path.indexOf(directLoadId) > -1 && this.content.indexOf(directLoadId) > -1 && !LBisActive) {
                this.activate();
                LBisActive = true;
            }
        } catch(e) {}
	},
	
	// Turn everything on - mainly the IE fixes
	activate: function(){
		if (browser == 'Internet Explorer' && version <= '6'){
			this.getScroll();
			//this.prepareIE('100%', 'hidden');
			var activeWrapper;
			activeWrapper = $('wrap');

			if (activeWrapper == null) {
				activeWrapper = $('wrapper');
			}

			wrapHeight = activeWrapper.getHeight();
			//wrapHeight = $('wrap').getHeight();
			this.prepareIE(wrapHeight, 'auto');
			//this.setScroll(0,0);
			this.hideSelects('hidden');
		}
		this.displaylightboxVideo("block");
		try {
			$('video-front-ads').hide();
			hide_trouble_elements();
		} catch (e){}
	},
	
	// Ie requires height to 100% and overflow hidden or else you can scroll down past the lightboxVideo
	prepareIE: function(height, overflow){

		
		bod = document.getElementsByTagName('body')[0];
		bod.style.height = height;
		bod.style.overflow = overflow;
		
		/*
		cont = document.getElementById('body_content');
		cont.style.height = height;
		cont.style.overflow = "hidden";
		*/
		
		htm = document.getElementsByTagName('html')[0];
		htm.style.height = height;
		htm.style.overflow = overflow; 
	},
	
	// In IE, select elements hover on top of the lightboxVideo
	hideSelects: function(visibility){
		selects = document.getElementsByTagName('select');
		for(i = 0; i < selects.length; i++) {
			selects[i].style.visibility = visibility;
		}
	},
	
	// Taken from lightboxVideo implementation found at http://www.huddletogether.com/projects/lightboxVideo/
	getScroll: function(){
		if (self.pageYOffset) {
			this.yPos = self.pageYOffset;
		} else if (document.documentElement && document.documentElement.scrollTop){
			this.yPos = document.documentElement.scrollTop; 
		} else if (document.body) {
			this.yPos = document.body.scrollTop;
		}
	},
	
	setScroll: function(x, y){
		window.scrollTo(x, y); 
	},

	// Begin Ajax request based off of the href of the clicked linked
	loadInfo: function() {

        info = "<div id='lbContentVideo'>"+
                "<div id='lbCloseVideo' class='lbClose' onclick='deactivateLBVideo()' ><div class='lbCloseInner'>Lukk videospiller [X]</div></div>" + 
                "<iframe id='videoFrame' scrolling='no' src='" + this.content + "'></iframe>" + 
                "<div id='lbCloseVideo2' class='lbClose' onclick='deactivateLBVideo()' ><div class='lbCloseInner'>Lukk videospiller [X]</div></div>"+
                "</div>";
        new Insertion.Before($('lbLoadMessageVideo'), info)                        
		//$('lbLoadMessageVideo').innerHTML = info;
        $('lightboxVideo').className = "done";
        
	},
	
    displaylightboxVideo: function(display){
		$('overlayVideo').style.display = display;
		$('lightboxVideo').style.display = display;        
		
		this.getScroll();
		$('lightboxVideo').style.top = this.yPos+50+'px';

		//return;
		if(display != 'none') this.loadInfo();
	},
	
	// Display Ajax response
	processInfo: function(response){

		info = "<div id='lbContent'>" + response.responseText + "</div>";
		new Insertion.Before($('lbLoadMessageVideo'), info)
		$('lightboxVideo').className = "done";	
		this.actions();			
	},
	
	// Search through new links within the lightbox, and attach click event
	actions: function(){

		lbActions = document.getElementsByClassName('lbAction');

		for(i = 0; i < lbActions.length; i++) {
			Event.observe(lbActions[i], 'click', this[lbActions[i].rel].bindAsEventListener(this), false);
			lbActions[i].onclick = function(){return false;};
		}

	},
	
	// Example of creating your own functionality once lightbox is initiated
	insert: function(e){

	   link = Event.element(e).parentNode;
	   Element.remove($('lbContent'));
	 
	   var myAjax = new Ajax.Request(
			  link.href,
			  {method: 'post', parameters: "", onComplete: this.processInfo.bindAsEventListener(this)}
	   );
	 
	},
	
	// Example of creating your own functionality once lightboxVideo is initiated
	deactivate: function(){

		Element.remove($('lbContentVideo'));
        //Element.remove($('lbClose'));
		
		if (browser == "Internet Explorer"){
			//this.setScroll(0,this.yPos);
			this.prepareIE("auto", "auto");
			this.hideSelects("visible");
		}
		
		this.displaylightboxVideo("none");
		
	}
}

function deactivateLBVideo(){
	Element.remove($('lbContentVideo'));
    			
	if (browser == "Internet Explorer" && version <= '6'){		
		window.scrollTo(0,lightboxVideo.prototype.yPos); 		
		
		bod = document.getElementsByTagName('body')[0];
		bod.style.height = "auto"
		bod.style.overflow = "auto";
		
		/*		
		cont = document.getElementById('body_content');
		cont.style.height = expression(document.documentElement.clientHeight-25);
		cont.style.overflow = "auto";
		*/
  
		htm = document.getElementsByTagName('html')[0];
		htm.style.height = "auto";
		htm.style.overflow = "auto"; 	
		
		selects = document.getElementsByTagName('select');
		for(i = 0; i < selects.length; i++) {
			selects[i].style.visibility = 'visible';
		}
	}	
    //$('videoFrame').src = 'about:blank';
	$('overlayVideo').style.display = 'none';
	$('lightboxVideo').style.display = 'none';	
	
	try  {
		$('video-front-ads').show();
		show_trouble_elements();
	} catch (e) {}
}

/*-----------------------------------------------------------------------------------------------*/

// Onload, make all links that need to trigger a lightboxVideo active

var init_lightbox = false;


function initialize_lightboxVideo(){
		
	
	addlightboxVideo_markup();
	
	// Kjører allerede i lightbox_scrollable (som kjøres på alle sider).
    // Denne må kjøres - for siter som ikke har lightbox_scrollable
	
	try {
		//var lbox = document.getElementsByClassName('lbOnVideo');
		var lbox = $$('a.lbOnVideo');
		
		for(i = 0; i < lbox.length; i++) {
		
			// Her kan det sjekkes om lbox[i] allerede er aktivert mtp lightbox 
			if (!lbox[i].hasClassName('lightbox_Active')) {
				valid = new lightboxVideo(lbox[i]);
				lbox[i].addClassName('lightbox_Active');
				lbox[i].style.visibility = "visible";
			}
			
		}
	} catch (e) {}

	$$('link_' + getkey('video'));
	
	init_lightbox = true;
}

// Add in markup necessary to make this work. Basically two divs:
// overlayVideo holds the shadow
// lightboxVideo is the centered square that the content is put into.

function addlightboxVideo_markup() {
	if (! $('overlayVideo')) {
        bod 				= document.getElementsByTagName('body')[0];
        overlayVideo       = document.createElement('div');
        overlayVideo.id    = 'overlayVideo';
        lbVideo            = document.createElement('div');
        lbVideo.id         = 'lightboxVideo';
        lbVideo.className  = 'loading';
        lbVideo.innerHTML  = '<div id="lbLoadMessageVideo"><p>Laster...</p></div>';
        bod.appendChild(overlayVideo);
        bod.appendChild(lbVideo);
    }
}

/**
* Function : dump()
* Arguments: The data - array,hash(associative array),object
*    The level - OPTIONAL
* Returns  : The textual representation of the array.
* This function was inspired by the print_r function of PHP.
* This will accept some data as the argument and return a
* text that will be a more readable version of the
* array/hash/object that is given.
*/
function dump(arr,level) {
	var dumped_text = "";
	if(!level) level = 0;
	
	//The padding given at the beginning of the line.
	var level_padding = "";
	for(var j=0;j<level+1;j++) level_padding += "    ";
	
	if(typeof(arr) == 'object') { //Array/Hashes/Objects 
		for(var item in arr) {
			var value = arr[item];
			
			if(typeof(value) == 'object') { //If it is an array,
				dumped_text += level_padding + "'" + item + "' ...\n";
				dumped_text += dump(value,level+1);
			} else {
				dumped_text += level_padding + "'" + item + "' => \"" + value + "\"\n";
			}
		}
	} else { //Stings/Chars/Numbers etc.
		dumped_text = "===>"+arr+"<===("+typeof(arr)+")";
	}
	return dumped_text;
}

        
function resizeLightbox(adWidth, adHeight, contentHeight) {
    // w = evt. width of skyscraper ad (180x500) 
    // h = evt. height of banner ad (768x150)
    
    if (browser == 'Internet Explorer' && version <= '6'){
        $('overlayVideo').style.height = '1000px';
    }
    var minWidth     = 790;
    var playerWidth  = 740;
    var playerHeight = 700;


    // Skin
    if (adWidth > 900 && adHeight >= 800) {
        adWidth  = 950;
        adHeight = 800;
    }
    
    // Banner & skyskraper
    else if (adWidth > 100 && adHeight > 100) {
        adWidth  = 930;
        adHeight = 700;
    }

    // Skin - gammel
    else if (adWidth == 'skin') {
        adWidth  = 930;
        adHeight = 800;
    }

    // Banner only
    else if (adWidth > 100 ) {
        adWidth  = 930;
        adHeight = 530;
    }

    // Skyskraper only
    else if (adHeight > 100 ) {
        adWidth  = 790;
        adHeight = 700;
    }

    // No ad
    else {
        adWidth  = 740;
        adHeight = 530;
    }

	adHeight += 32; // New controlbar
    

    $('videoFrame').setStyle({
        width:  adWidth + 'px',
        height: adHeight + 'px'
    });

    $('lightboxVideo').setStyle({
        width:      adWidth + 'px',
        height:     adHeight + 'px',
        marginLeft: '-' + adWidth/2 + 'px',
        width:      adWidth + 20 + 'px'
    });


    // Viser lukkeknappene
    $('lbCloseVideo').setStyle({zIndex:'1200', display:'block'});
    $('lbCloseVideo2').setStyle({zIndex:'1300', display:'block'});

    // Sørger for riktig plassering av lukkeknappene
    if (browser == "Gecko"){		
        $('lbCloseVideo').absolutize().setStyle({top:'0px', marginTop:'-20px', right:'0px', marginRight:'10px'});
        $('lbCloseVideo2').absolutize().setStyle({top:'auto', bottom:'10px', right:'0px', marginRight:'10px'});
    }
}


function setVideoHeight (videoHeight){
    $('videoFrame').setStyle({
		height: videoHeight
    });	
	
	if (browser == "Gecko"){
        //setTimeout("			console.log('xx'); 			t=" + videoHeight + ";			console.log ('t: ' + t);			$('lbCloseVideo2').setStyle({top:t})			", 500);
		$('lbCloseVideo2').setStyle({top:videoHeight});
    }

}


function onMyTextKeypress(event){
	if (Event.KEY_ESC == event.keyCode) {
		//alert('Esc was pressed.');
		deactivateLBVideo();
	}
	return;
}


Element.addMethods('iframe', {
	document: function(element) {
	  element = $(element);
	  if (element.contentWindow)
		  return element.contentWindow.document;
	  else if (element.contentDocument)
		  return element.contentDocument;
	  else
		  return null;
	},
	$: function(element, frameElement) { 
	  element = $(element);
	  var frameDocument = element.document();
	  if (arguments.length > 2) {
		  for (var i = 1, frameElements = [], length = arguments.length; i < length; i++)
			  frameElements.push(element.$(arguments[i]));
		  return frameElements;
	  }
	  if (Object.isString(frameElement))
		  frameElement = frameDocument.getElementById(frameElement);
	  return frameElement || element;
	}
});



function getKey (key, query) {
	if (!query)
		query = window.location.search;    
	var re = new RegExp("[?|&]" + key + "=(.*?)&");
	var matches = re.exec(query + "&");
	if (!matches || matches.length < 2)
		return false;
	return decodeURIComponent(matches[1].replace("+", " "));
}
