// JavaScript Document

function wrapNice(){
	var allNice = $$('div.nice');
	for(var d=0;d<=allNice.length;d++){
		if(allNice[d]){
			allNice[d].update('<img src="/Templates/04resources/images/side_block_top.jpg" class="niceTop" /><img src="/Templates/04resources/images/side_block_bottom.jpg" class="niceBottom" /><div class="niceContent">'+allNice[d].innerHTML+'</div>');
			if(allNice[d].getHeight() < 93)
				allNice[d].setStyle({height:'93px'});
		}
	}
}

function a_tabs(){
	$$('.a_tabs a').each( function(a){
			if(isSel = a.hasClassName('sel')){a.removeClassName('sel');}
		   var box = a.className;
		   a.href = "javascript:a_tabsShow('"+box+"');";
		   if(isSel){a.addClassName('sel');}
	   });
}
function a_tabsShow(box){
	$$('.a_tabs a').invoke('removeClassName','sel');
	$$('.a_tabContent').invoke('hide');
	$$('.a_tabContent.'+box).invoke('show');
	$$('.a_tabs a.'+box).invoke('addClassName','sel');
}


//NEWS CONTENT ROTATION
var mainDiv = new Array();
var contentDiv = new Array();
var mH = new Array();
var cH = new Array();
var nextMove = new Array();
var cTop = new Array();
function startMoveNews(){
	mainDiv = $$('div.newsAndEventsSide');
	for(a=0;a<mainDiv.length;a++){
		contentDiv[a] = mainDiv[a].firstDescendant();
		mH[a] = mainDiv[a].getHeight();
		cH[a] = contentDiv[a].getHeight();
		nextMove[a] = -mH[a];
		cTop[a] = 0;
		setTimeout('moveNewsContent('+a+')',6000);
	}
	
}
function moveNewsContent(a){
	if(cH[a]==0 || mH[a]==0){
		//because IE is special
		mH[a] = mainDiv[a].getHeight();
		cH[a] = contentDiv[a].getHeight();
		setTimeout('moveNewsContent('+a+')',1000);
		return;
	}
	if(cH[a]>mH[a]){
		if((cTop[a]>nextMove[a] && nextMove[a]<0) || (cTop[a]<nextMove[a] && nextMove[a]==0)){
			var inc = Math.round((nextMove[a]-cTop[a])/2);
			if(inc==0){inc=-1;}
			cTop[a]+=inc;
			contentDiv[a].setStyle({top:cTop[a]+'px'});
			setTimeout('moveNewsContent('+a+')',100);
		}else{
			contentDiv[a].setStyle({top:nextMove[a]+'px'});
			cTop[a] = nextMove[a];
			nextMove[a] = nextMove[a]-mH[a];
			if(-nextMove[a]>=cH[a]){nextMove[a]=0;}
			setTimeout('moveNewsContent('+a+')',8000);
		}
	}
}

//POP-UP
function showPopUp(uri){
	if(!$('popUpWindow')){
		var theBody = Element.extend(document.body);
		theBody.insert({bottom:'<div class="windowWrap" id="popUpWindow" style="display:none;"><div class="windowTop" onclick="$(\'popUpWindow\').hide();"></div><div class="window">&nbsp;</div><div class="windowBottom"></div></div>'}); 
	}
	var winTop = document.viewport.getScrollOffsets().top;
	if(winTop<50){winTop+=100;}else{winTop+=10;}
	new Ajax.Request(uri,{
		onSuccess: function(response){
			$('popUpWindow').setStyle({top:winTop+'px'}).show().select('.window')[0].update(response.responseText);
            if(showPopUp.successFunction != undefined){
                showPopUp.successFunction()
            }
		}
	});
}

//PROFILE DISPLAY
function showProfile(theName){
	showPopUp('/about/people/profiles/'+theName+'.php?in=true');
}

function showSharePopUp(note, shareUrl){

    if(shareUrl != undefined && shareUrl!='')
        showSharePopUp.shareUrl = shareUrl;
    else
        showSharePopUp.shareUrl = location.href;

    if(note != undefined && note != '')
        showSharePopUp.note = note;
    else
        showSharePopUp.note = 'You may be interested in this.';

    showPopUp.successFunction = function(){
        var queryVars = location.search.toQueryParams();
        if(queryVars.first !== undefined)
            $('shareFirst').value = queryVars.first
        if(queryVars.last !== undefined)
            $('shareLast').value = queryVars.last
        if(queryVars.email !== undefined)
            $('shareEmail').value = queryVars.email
        $('shareMessage').value = showSharePopUp.note;
        updateHeight('shareMessage');
        $('shareLinkField').value = showSharePopUp.shareUrl;
        $('shareLink').update(showSharePopUp.shareUrl);
        $$('.shareName').invoke('update',$('shareFirst').value);
        if($('shareLast').value != 'Last name')
            $$('.shareLast').invoke('update',$('shareLast').value);
    }
    showPopUp('/_elements/ajax/shareWithFriend_popup/shareForm.php');
}

function clearVal(input, value){
    if(input.value == value){
        input.value = '';
    }
    $(input).removeClassName('placeholderText');
}
function defaultVal(input, value){
    if(input.value == ''){
        input.value = value;
        $(input).addClassName('placeholderText');
    }
}
function updateHeight(element){
    element = $(element);
    element.setStyle({height:'0px'});
    element.setStyle({height:element.scrollHeight+'px'});
    if(element.getHeight()<16)
        element.setStyle({height:'16px'});
}
function submitShareWithFriendForm(){
    $('shareSubmit').writeAttribute('disabled', true).writeAttribute('value', 'Sending...');
    var pass = true;
    
    $$('#shareToError').invoke('remove');
    var to = $('shareTo');
    to.value = to.value.replace("\n",',').replace("\r",',').replace(',,',',').replace(',,',',');
    var emails = to.value.match(/[0-9a-zA-Z\.\-_]+@[0-9a-zA-Z\.\-_]{2,}\.[0-9a-zA-Z]{2,3}/g);
    if(emails == null || emails.length < 1){
        to.insert({before:'<span style="color:red" id="shareToError"><br/>Please enter at least one email address.</span>'});
        pass = false;
    }
    
    $$('#shareEmailError').invoke('remove');
    var email = $('shareEmail');
    var emailValid = email.value.match(/^[0-9a-zA-Z\.\-_]+@[0-9a-zA-Z\.\-_]{2,}\.[0-9a-zA-Z]{2,3}$/);
    if(emailValid == null || emailValid>1 || emailValid < 1){
        email.insert({before:'<span style="color:red" id="shareEmailError">Please enter a valid email address.</span>'});
        pass = false;
    }
    
    $$('#shareFirstError').invoke('remove');
    var first = $('shareFirst');
    if(first.value == 'First name' || first.value == ''){
        first.insert({before:'<div style="color:red;" id="shareFirstError">Please enter at least your first name.<br/></div>'});
        pass = false;
    }
    
    if(!pass){
        $('shareSubmit').writeAttribute('disabled', false).writeAttribute('value', 'Send');
    }else{
        var data = $('shareForm').serialize();

        new Ajax.Updater('shareForm','/_elements/ajax/shareWithFriend_popup/shareSubmit.php',{
            parameters: data,
            evalScripts: true
        });
    }
}

// DOWNLOAD BUTTON
function activateDownloadButton(){
	var dButtons = $$('img[src="/_elements/userfiles/image/content/download.gif"]');
	if(dButtons.length>0){
		var overImage = new Image;
		overImage.src = '/_elements/userfiles/image/content/downloadFrames/f2.gif';
		var downImage = new Image;
		downImage.src = '/_elements/userfiles/image/content/downloadFrames/f3.gif';
		for(var b=0;b<dButtons.length;b++){
			var id = dButtons[b].identify();
			dButtons[b].onmouseover = function(){
				this.src = overImage.src;
				}
			dButtons[b].onmouseout = function(){
				this.src = '/_elements/userfiles/image/content/download.gif';
				}
			dButtons[b].onmousedown = function(){
				this.src = downImage.src;
				}
		}
	}
}

// Collapse Document
function collapse(div, header){
	var theDiv = $(div)
	var curH = theDiv.getHeight();
	if(curH > 50){
		curH -= 50;
		theDiv.setStyle({height: curH+'px'});
		setTimeout("collapse('"+div+"','"+header+"');",100);
	}else{
		theDiv.setStyle({height: '0px'});
		var theHead = theDiv.previousSiblings().find(function(s){return s.tagName.toLowerCase() == 'h'+header});
		theHead.onclick = function(){expand(div,header);}
		theHead.select('span.headTag')[0].update('[Click&nbsp;to&nbsp;Expand]');
	}
}
function expand(div,header){
	var theDiv = $(div)
	var curH = theDiv.getHeight();
	var inDiv = theDiv.select('div')[0];
	inDiv.firstDescendant().setStyle({marginTop:'0px'}).firstDescendant().setStyle({marginTop:'0px'});
	var endH = inDiv.getHeight();
	
	if(curH < endH - 50){
		curH += 50;
		theDiv.setStyle({height: curH+'px'});
		setTimeout("expand('"+div+"','"+header+"');",100);
	}else{
		theDiv.setStyle({height: endH+'px'});
		var theHead = theDiv.previousSiblings().find(function(s){return s.tagName.toLowerCase() == 'h'+header});
		theHead.onclick = function(){collapse(div,header);}
		theHead.select('span.headTag')[0].update('[Click&nbsp;to&nbsp;Collapse]');
	}
}
function startCollapse(header){
	var heads = $$('.mainDiv h'+header);
	for(var h=0;h<heads.length; h++){
		var toCollapse = heads[h].nextSiblings();
		var outSideHolder = Element.extend(document.createElement('div'));
		outSideHolder.setStyle({overflow:'hidden'});
		var outSideId = outSideHolder.identify();
		var inSideHolder = Element.extend(document.createElement('div'));
		/*var inSideId = outSideHolder.indentify();*/
		heads[h].insert({after:outSideHolder});
		outSideHolder.insert({top:inSideHolder});
		heads[h].update(heads[h].innerHTML+' &nbsp; <span class="headTag"></span>');
		heads[h].setStyle({cursor:'pointer'});
		heads[h].onclick = function(){expand(outSideId,header);}
		for( var c=0;c<toCollapse.length;c++){
			var thisTag = toCollapse[c].tagName.toLowerCase();
			if( thisTag == 'h'+header || thisTag == 'h'+(header-1) || thisTag == 'h'+(header-2) || thisTag == 'h'+(header-3) || thisTag == 'h'+(header-4) || thisTag == 'h'+(header-6)){
				break;
			}
			if(!toCollapse[c].hasClassName('doNotCollapse') && thisTag != 'script'){
				inSideHolder.insert({bottom:toCollapse[c]});
			}
		}
		collapse(outSideId,header);
	}
	//alert(minHs);
}

function GWtrackThis(path){
	if(window.pageTracker){
		pageTracker._trackPageview(path);
	}
}

function GWlogin(){
	document.location = location.pathname+'?secureFunction=adminLogin';
}

function GWformatTable(){
	$$('.a_tableFormatted tr').each( 
		function(tr){
			tr.onmouseover = function(){
				this.addClassName('hover');
				/*this.select('td').each( function(td){ 
							td.addClassName('hover'); 
				}) */
			}
			tr.onmouseout = function(){
				this.removeClassName('hover');
				/*this.select('td').each( function(td){ 
							td.removeClassName('hover'); 
				}) */
			}
			var a;
			if( a = tr.select('a')[0] ){
				var href = a.href;
				tr.onclick = function(){
					location.href = href; 
				}
				a.removeAttribute('href');
			}
		});
}

function GWcollapseDiv(){
	$$('div.collapse h3').each( function(h){
									h.siblings().invoke('hide');
									Event.observe(h, 'click', function(){h.siblings().invoke('toggle');});
								})
}

function donationPopup(link){
    donationPopup.link = link;
    var div = $$('.donation_popup');
    if(div.length==0){
        var cssLink = new Element('link');
        cssLink.rel = 'stylesheet';
        cssLink.type = 'text/css';
        cssLink.href = '/_elements/ajax/donation_popup/popup.css';
        $$('head')[0].insert({bottom:cssLink});
        new Ajax.Updater($(document.body), '/_elements/ajax/donation_popup/popup.html',{
            insertion: Insertion.Bottom,
            onComplete: function(){
                var donationPopup = $$('.donation_popup');
                var pos = $(window.donationPopup.link).cumulativeOffset();
                donationPopup[0].setStyle({top:(pos.top+5)+'px',left:(pos.left+20)+'px'});
            },
            evalScripts: true
        });
        
    }else{
        var pos = $(link).cumulativeOffset();
        div[0].setStyle({top:(pos.top+5)+'px',left:(pos.left+20)+'px'}).show();
    }
}

//FUNCTION LAUNCHER
//Event.observe(window, 'load', function() {
function startGWJS(){	//started from bottom.php
	wrapNice();
	startMoveNews();
	activateDownloadButton();
	GWformatTable();
	GWcollapseDiv();
	Event.observe('george', 'click', GWlogin);
}
//});
