var initRatings = null;
window.addEvent('domready', function() {
	
	if($("SectionButtons")) {
		$("sectionLnk1").addEvent("mouseenter", function(){switchBG($$("div[class=TopImageFirstpage]")[0], "topFP1.jpg")});
		$("sectionLnk2").addEvent("mouseenter", function(){switchBG($$("div[class=TopImageFirstpage]")[0], "topFP2.jpg")});
		$("sectionLnk3").addEvent("mouseenter", function(){switchBG($$("div[class=TopImageFirstpage]")[0], "topFP3.jpg")});
		$("sectionLnk4").addEvent("mouseenter", function(){switchBG($$("div[class=TopImageFirstpage]")[0], "topFP4.jpg")});
	}
	
	//if($("MainMenu")) {
	//	var objMagicMenu = new GradientMenu({element:$("MainMenu"),color:"#041067",gradientPercent:30});
	//}
	
	if($("BookmarksWindow"))
	{
		/* $("BookmarksWindow").set('style', 'height:0px'); */
		$("BookmarksWindow").set({'opacity':0});
	}
	
	/*
	initInjectionkitHover();
	*/
	
	if($("ratings")) {
		initRatings = $('ratings').clone(true, false);
		$("ratings").addEvent("mouseleave", mouseLeftRatings);
	}

});

function initInjectionkitHover()
{
	if($('InjectionKit')) {
		$('InjectionKit').addEvent('mouseenter', function(){
			if(!$('InjectionKitText')) {
				$('InjectionKit').adopt(new Element('div',{'id':'InjectionKitText'}).setText('Coming soon! The emla pre-medication pack provides everything you need to ensure appropriate use of emla (including dressings and an information leaflet.)'));
				$('InjectionKitText').setOpacity(0.9);
			} else {
				$('InjectionKit').adopt($('InjectionKitText'));
				$('InjectionKitText').setOpacity(0.9);
			}
			
		});
		$('InjectionKit').addEvent('mouseleave', function(){
			$('InjectionKitText').remove();
		});
	}
}	

function call(func, arg)
{
	var erg = function() {
		func(arg);
	}
	
	return erg;
}

function cleanup(arElms)
{
	// 0 = parent
	// 1 = the new element
	
	arElms[0].getChildren().each(function(elm){elm.remove()}); // remove all children
	arElms[0].adopt(arElms[1]); //reattach the new elemnt
	
	// Fix the style
	arElms[1].setStyle('z-index', '2');
	arElms[1].setStyle('opacity', '1');
}


function switchBG(elmDiv, strNewBg) {
	var newElm = elmDiv.clone().injectAfter(elmDiv);
	newElm.setStyle('background-image', 'url(../imgs/'+strNewBg+')');
	newElm.setStyle('z-index', '1');
	
	elmDiv.set('morph', {duration: 200, transition: 'quad:out',onComplete:call(cleanup, [elmDiv.getParent(), newElm])});
	elmDiv.morph({'opacity':0});
}

function toggleBookmarks()
{
	var bw = $("BookmarksWindow");
	bw.set('morph', {duration: 250, transition: Fx.Transitions.Quad.easeOut});
	if(bw.getStyle('opacity') == 0) {
		bw.morph({
			'opacity':1
		});	
	} else {
		bw.morph({
			'opacity':0
		});
	}
}


function sendToFriend()
{
	mystring = window.location.href;
	mystring = mystring.replace(/&/ig,'&amp;'); 
	sendWin = window.open('/index.asp?did=34102&ArticleLink='+escape(mystring),'sendWin','width=400,height=500,resizable=yes,scrollbars=yes')
}


function showTerms(bolForced, specialCase)
{
	if($('acceptterms').checked == false || bolForced == true)
	{
		$('ntnTerms').style.display = 'block';
	}
	
	if(specialCase == 'uploadForm') {
		$('ntnTerms').style.top = '180px';
	}
}

function closeTerms()
{
	$('ntnTerms').style.display = 'none';
}

/* Video rec page */
var currentView = null;
function transformTo(strTargetID)
{
	if(currentView == null)
		currentView = $('ChooseMethod');
	
	var targetHeight = $(strTargetID).scrollHeight;
	
	$(strTargetID).set('style',{'opacity':0}); // Target should start transparent
	
	$(strTargetID).set('morph', {duration: 500, transition: 'quad:out'});
	$(strTargetID).morph({'opacity':1,'height':targetHeight});
	
	currentView.set('morph', {duration: 500, transition: 'quad:out'});
	currentView.morph({'opacity':0,'height':0});
	
	currentView = $(strTargetID);
}

function SaveText()
{
	// witch to loading page
	transformTo("LoadingDiv");
	
	var ContribRequest = new Request({method: 'post', url: '/AddContribution.asp'});
	
	ContribRequest.send($('TextForm').toQueryString());
	
	ContribRequest.onException = function(headerName, value)
	{
		alert("Upload exeption:/n"+headerName+": "+value);
	}
	
	ContribRequest.onSuccess = function(responseText, ResponseXML)
	{
		//alert(responseText + " ## "+ ResponseXML);
		setTimeout(function(){transformTo("SubmitDone");}, 2000);
	}
}

function SaveContribution()
{
	// witch to loading page
	transformTo("LoadingDiv");
	
//	alert($('RecordForm').toQueryString())
	
	var ContribRequest = new Request({method: 'post', url: '/AddContribution.asp'});
	
	//alert('strFlv:' + $('strFlvRecord').value)
	
	//alert($('RecordForm').toQueryString())
	
	ContribRequest.send($('RecordForm').toQueryString());
	
	ContribRequest.onFailure = function(instance)
	{
		alert("Thumbnail IE error. :"+this);
	}
	
	ContribRequest.onException = function(headerName, value)
	{
		alert("Upload exeption:/n"+headerName+": "+value);
	}
	
	ContribRequest.onSuccess = function(responseText, ResponseXML)
	{
		//alert(responseText + " ## "+ ResponseXML);
		setTimeout(function(){transformTo("SubmitDone");}, 2000);
	}
}

function UploadContribution(step)
{
	
	/*
		Steps:
		
		1. 	Get a guid for the filename. This step will allways be taken, but only
			video uploads will make use of the obtained GUID.
			If a YouTube link is detected in this step, it will skip to step 3.
			
		2. 	Upload file to the sorenson server, alt. the image upload script on
			this server
			
		3. 	Create an article for the upload in DC
	*/
	
	switch(step)
	{
		////////////////////////////////////////////////////////////////////////
		case 1:
			//alert("upload step 1");
			if($("strYouTubeLnk").value != "") {
				if($('strYouTubeLnk').value.indexOf('watch?v=')>0) {
					transformTo("LoadingDiv");
					$("intContribType").value="1";
					UploadContribution(3);
				} else {
					alert("Please make sure the the YouTube URL is correct.");
				}
			} else {
				var ContribRequest = new Request({method: 'get', url: '/GetGuid.asp'});
				ContribRequest.send();
				ContribRequest.onSuccess = function(responseText)
				{
					transformTo("LoadingDiv");
					$('strGUID').value = responseText.substring(1).substring(0,responseText.length-2);
					UploadContribution(2);
				}
			}
		break;
		////////////////////////////////////////////////////////////////////////
		
		
		////////////////////////////////////////////////////////////////////////
		case 2:
			if($("strFileUpload").value.test(".jpeg") || $("strFileUpload").value.test(".jpg") || $("strFileUpload").value.test(".gif")) {
		// Image upload
				
				$("fileUploadForm").action = "/ImgUpload.asp";
				$("fileUploadFrame").addEvent("load", iframeDoneLoading);
				$("fileUploadForm").submit();
				
			} else if($("strFileUpload").value.test(".wmv", "i") || $("strFileUpload").value.test(".mpg", "i")
			|| $("strFileUpload").value.test(".mov", "i") || $("strFileUpload").value.test(".avi", "i")) {
		// Video upload
				$("intContribType").value="1";
				$("strUploadThumbnail").value = $('strGUID').value+".jpg";
				$("fileUploadForm").action = "http://89.253.86.14/VideoUpload.asp?providedGuid="+$('strGUID').value;
				$("fileUploadFrame").addEvent("load", iframeDoneLoading);
				$("fileUploadForm").submit();
				
			} else {
				alert("The file you have selected for upload is not valid");
			}
		break;
		////////////////////////////////////////////////////////////////////////
		
		
		////////////////////////////////////////////////////////////////////////
		case 3:
			var ContribRequest = new Request({method: 'get', url: '/AddContribution.asp'});
			ContribRequest.send($('UploadForm').toQueryString());
			ContribRequest.onSuccess = function()
			{
				setTimeout(function(){transformTo("SubmitDone");}, 2000);
			}
		break;
		////////////////////////////////////////////////////////////////////////
	}
}

function iframeDoneLoading(response)
{	
	try {
		var strImageFilename = window.frames["fileUploadFrame"].document.getElementById("strFileName").value;
		$("strImageName").value = strImageFilename;
		$("strUploadThumbnail").value = "thumb_"+strImageFilename;
	} catch(e) {
		// Don't mind this kind of error
	}
	
	UploadContribution(3);
}

// Called upon by the flash
function setMovieName(strFilename)
{
	
	$('strFlvRecord').value = strFilename;
	$('strVidThumbnail').value = strFilename+'.jpg';
	$('btnNext').disabled = false;
}

//Rating vote
function rV(obj)
{
	if($('pollaid') && $('pollaid').value != '')
	{
		alert("rV - pollaid OK");
		if(readCookie(window.location.href) != "true") {
			if(confirm('Do you wish to rate this contribution with a '+  obj.getAttribute('alt') +' star rating?'))
			{
				createCookie(window.location.href, 'true', 365);
				
				$('vote').value = obj.getAttribute('alt');
				
				var VoteRequest = new Request({method: 'post', url: $('voteForm').action});
				VoteRequest.send($('voteForm').toQueryString());
				
				VoteRequest.onSuccess = function()
				{
					alert("Your rating has been recorded!");
				}
			}
		} else {
			alert('You have already voted on this page')
		}
	}
}

// Hoover the ratings
var stop = false;
function rHoover(elmHoovered)
{
	$('ratings').getElements('img').each(function(elm, index){
		
		elm.src = "/imgs/rE.gif";
		
		if(!stop)
			elm.src="/imgs/rF.gif";
		
		if(elm == elmHoovered)
			stop = true;
	}.bind(elmHoovered));
	
	stop = false;
}

function rUnHoover(elmHoovered)
{
	// nope
}

function mouseLeftRatings(e)
{
	$('ratings').getParent().adopt(initRatings);
	$('ratings').destroy();
	initRatings.id = 'ratings';
	
	initRatings = null;
	initRatings = $('ratings').clone(true, false);
	$('ratings').addEvent("mouseleave", mouseLeftRatings);
}

function charsLeft(obj,intLimit)
{
	if(obj.value.length > intLimit)
	{
		alert('This field may only contain '+intLimit+' characters.');
		obj.value = obj.value.substring(0,intLimit);
	}
}

function changeCategory(obj)
{
	if(obj.selectedIndex != 0)
	{
		if($('catForm1'))
		{
			$('catForm1').submit();
		}
		if($('catForm2'))
		{
			$('catForm2').submit();
		}
	}

}

function changeCategoryName(obj)
{
	if(obj.selectedIndex != 0)
	{
		if($('catForm1'))
		{
			window.location.href = obj.options[obj.selectedIndex].value + '&mid=8';
		}
		if($('catForm2'))
		{
			window.location.href = obj.options[obj.selectedIndex].value + '&mid=8';
		}
	}

}

function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}

function randomizeBanner()
{
	var toBanner;
	
	switch(Math.floor(Math.random()*4))
	{
		case 0:
			toBanner = 'DisneyBanner';
		break;
		case 1:
			toBanner = 'SpaBanner';
		break;
		case 2:
			toBanner = 'SafariBanner';
		break;
		case 3:
			toBanner = 'TravelBanner';
		break;
	}
	
	$("bannerHolder").childNodes[0].id = toBanner;
	
	setTimeout(randomizeBanner, 10000);
	
}
