var previousOpenedAnswer = null;
function toggleAnswer(highlight, Params){



		 if (document.getElementById(Params).style.display == "") {
			
			document.getElementById(Params).style.display = "none"; 
			document.getElementById(highlight).style.color='';  


		  } else {
		  	if(previousOpenedAnswer != null){
		  		document.getElementById(previousOpenedAnswer).style.display = "none";
		  		document.getElementById(highlight).style.color=''; 
		  	}
			previousOpenedAnswer = Params;
			document.getElementById(Params).style.display = "";
			document.getElementById(highlight).style.color='red';           
		  }
}

function toggleCategory(Params){
		
		var innerDivs = document.getElementById(Params).getElementsByTagName('div');
		var newStyle = "";
		for (var i=0; i < innerDivs.length; i++){
		 	if (i==0 && innerDivs[0].style.display == "") {
		 		newStyle = "none";
		 		document[Params+"_image"].src = document[Params+"_image"].src.replace("minus","plus");
			}
			
			innerDivs[i].style.display = newStyle;

		}
		
		if(newStyle=="none"){
		 		document[Params+"_image"].src = document[Params+"_image"].src.replace("minus","plus");
		}
		else{
		 		document[Params+"_image"].src = document[Params+"_image"].src.replace("plus","minus");
		}
		
		refreshSortables();
}

function toggleDiv(Params){
	 if (document.getElementById(Params).style.display == "") {
		
		document.getElementById(Params).style.display = "none";  


	  } else {
		document.getElementById(Params).style.display = "";          
	  }
}

function refreshSortables(){
	for(var i = 0; i < mySections.length; i++) {
			var myDiv = document.getElementById(mySections[i]);
			myDiv.style.left = 1;
			myDiv.style.left = 0;
	}
}

function updateQuestionText(questionText){
	alert(questionText);
	document.getElementById('questionText').innerHTML = questionText;
}


function updateResourceOrder()
{
    var options = {
                    method : 'post',
                    parameters : Sortable.serialize('resource_list')
                  };
 
    new Ajax.Request('getresourceranking', options);
}

function updateCategoryOrder()
{
    var options = {
                    method : 'post',
                    parameters : Sortable.serialize('category_list')
                  };
 
    new Ajax.Request('getcategoryranking', options);
}

function updateCategoriesOnServer(){
// mySections is previously defined when we come back from our ajax call
// to get the list of sections, we go through each one and create a param list to send
	var sections = document.getElementsByClassName('section');
	var str = "";
	var temp;
		for (var i=0; i < sections.length; i++){
			temp = (Sortable.serialize(sections[i].id));
			if (temp.length == 0){
				str += sections[i].id + "=" + i;
			}else{
				str += temp;
			}
			
			if (i < (sections.length-1)){
				str+= "&";
			}
		}
		
	var options = {
                    method : 'post',
                    parameters : str
                  };
 
    new Ajax.Request('updatecategoryranking', options);

	refreshSortables();
}


function getCategories(section)
{
    	new Ajax.Request('getcategories?section=' + section  + '&time=' + new Date().getTime(),
  	{
	    method:'get',
	    onSuccess: function(transport){
			var catList = new Array();

			catList = transport.responseText.split("\n");
			var options = document.forms["resource"].categories.options;
			options.length = 0;
			for (i=0; i < catList.length -1; i++){
				var id = catList[i].substring(0, catList[i].search("|")+1);
				var name = catList[i].substring(catList[i].search("|")+2, catList[i].length);
				
				options[options.length] = new Option(name, id);
			}
	    },
    	onFailure: function(){ alert('Something went wrong...') }
  	});
}



function getCategoriesSortable(section)
{
    	new Ajax.Request('getcategoriessortable?section='+section+'&time=' + new Date().getTime(),
  	{
    	
	    method:'get',
	    onSuccess: function(transport){
	      var divToUpdate = $('updateableSection');
	      var response = transport.responseText || "no response text";
	      divToUpdate.update = 'test';
	      
	      var parts = response.split("@JAVASCRIPT@");
	      
	      var noReturnJs = parts[0].replace(/\n/g, "");
	     
	      document.getElementById('updateableSection').innerHTML=parts[1];
	      eval(noReturnJs);
		  
	    },
    	onFailure: function(){ alert('Something went wrong...') }
  	});
}

	function deleteCategory(categoryId){
			new Ajax.Request('deleteCategory?categoryId='+categoryId+'&time=' + new Date().getTime(),
		  	{
			    method:'get',
			    onSuccess: function(transport){
				      //we need to remove the div from the sortable list and from the page
	
				    //Effect.Fade('group_'+categoryId);
				    
				    $('updateableSection').removeChild($('group_'+categoryId));
				   
				    for(var i = 0; i < mySections.length; i++) {
				   
						if(mySections[i]== 'group_'+categoryId){
							mySections.splice(i,1);
						}
					}

					refreshSortables();
			    },
		    	onFailure: function(){ alert('Something went wrong...') }
		  	});
	}
	
	function deleteResource(resourceId, categoryId){
			new Ajax.Request('deleteResource?resourceId='+resourceId+'&time=' + new Date().getTime(),
		  	{
			    method:'get',
			    onSuccess: function(transport){
				      //we need to remove the div from the sortable list and from the page
	
				    //Effect.Fade('group_'+categoryId);
				    
				    $('group_'+categoryId).removeChild($('item_'+resourceId));
				    
				    //for(var i = 0; i < mySections.length; i++) {
						//if(mySections[i]== 'item_'+resourceId){
							
							//mySections.remove(i);
						//}
					//}
					refreshSortables();
			    },
		    	onFailure: function(){ alert('Something went wrong...') }
		  	});
	}

	function createNewSection(sectionType, imagesLocation) {
	
		var name = $F('sectionName');
		var newID = null;
		var sectionId = $F('sectionId');
		
		var newHref = "";
		var newLink = "";
		


		if (name != '') {
			
		    	new Ajax.Request('addCategory?section='+sectionId+'&category='+name+'&time=' + new Date().getTime(),
		  	{
			    method:'get',
			    onSuccess: function(transport){
			      	newID = transport.responseText;
			      	//new
			      	
					if(sectionType == 'PHOTO'){
						newHref = "photoAdmin?categoryId=" + newID;
						newLink = "Add Media";
					}
					else if(sectionType == 'DOCUMENT'){
						newHref = "documentAdmin?categoryId=" + newID;
						newLink = "Add Document";
					}
					else if(sectionType == 'QUESTION'){
						newHref = "questionAdmin?categoryId=" + newID;
						newLink = "Add Question";
					}
					else if(sectionType == 'LINK'){
						newHref = "linkAdmin?categoryId=" + newID;
						newLink = "Add Link";
					}
					else if(sectionType == 'EVENT'){
						newHref = "eventAdmin?categoryId=" + newID;
						newLink = "Add Event";
					}
					else if(sectionType == 'ARCHIVE'){
						newHref = "archiveAdmin?categoryId=" + newID;
						newLink = "Add Archive";
					}
					
					var editHref = "categoryAdmin?categoryId=" + newID + "&sectionId=" + sectionId;
					
					var newDiv = Builder.node('div', {id: 'group_' + newID, className: 'section', style: 'display:;' }, 
									[Builder.node('h3', {className: 'handle'},
										[Builder.node('table', {width: '100%'},
											[Builder.node('tbody', {}, 
												[Builder.node('tr', {},
													[Builder.node('td', {width:'2%'},
														[Builder.node('img', {src: imagesLocation, onclick:'toggleCategory("group_' + newID + '");', className:'expandHover', name: 'group_' + newID + '_image'})]),
													 Builder.node('td', {width:'68%'},name),
													 Builder.node('td', {className: 'categoryFunctions', width:'30%', align:"right"},
														[Builder.node('a', {href: newHref }, newLink),' | ',
														 Builder.node('a', {href:'#'}, 'Edit'),' | ',
														 Builder.node('a', {href:'#', onclick:'deleteCategory(' + newID + ');'}, 'Delete')]
													)])])])])]);
					
					
		
					mySections.push(newDiv.id);
					
					$('createNew').insert({after:newDiv});
		
					//Effect.Appear(newDiv.id);
					
					destroyLineItemSortables();
					createLineItemSortables();
					createGroupSortable();
					
					updateCategoriesOnServer();
					//refreshSortables();
			    },
		    	onFailure: function(){ alert('Something went wrong...') }
		  	});


		}
	}

	function createLineItemSortables() {
		for(var i = 0; i < mySections.length; i++) {
			Sortable.create(mySections[i],{tag:'div',dropOnEmpty: true, containment: mySections,only:'lineitem', onUpdate: updateCategoriesOnServer});
		}
	}

	function destroyLineItemSortables() {
		for(var i = 0; i < mySections.length; i++) {
			Sortable.destroy(mySections[i]);
		}
	}

	function createGroupSortable() {
		Sortable.create('updateableSection',{tag:'div',only:'section',handle:'handle',onUpdate: updateCategoriesOnServer});
	}
	
	function toggleEffect(Params){

			 if (document.getElementById(Params).style.display == "") {
			 
			    document[Params+"image"].src = document[Params+"image"].src.replace("minus","plus");  
			 	
				//document[Params+"image"].src="test";
				
				Effect.SlideUp(Params); return false;
				
				
	
	
			  } else {
				document[Params+"image"].src = document[Params+"image"].src.replace("plus","minus");
				Effect.SlideDown(Params); return false;     
				             
	
			  }
	}
	
	function changePage(selectBox){

		window.location = "edit?id=" + selectBox.value;
	}
	
// Email stuff
	
	function saveEmailAddressAdmin() {
		
		
		emailAddress = document.forms["adminmaillistform"].email.value;
		
		if (echeck(emailAddress) == false) {
			return;
		}
		
		new Ajax.Request('saveemail?email=' + emailAddress + '&time=' + new Date().getTime(),
		{
			method:'get',
			onSuccess: function(transport) {
				
				newID = transport.responseText;	

				var newDiv = Builder.node('tr', { id: 'notification' + newID }, 
											[Builder.node('td', {width: '200'}, emailAddress),
											 Builder.node('td', {width: '200'}, [
												Builder.node('a',{href: '#', onclick: 'deleteNotification(' + newID + ');'}, 'Delete') ])]); 		
				
				$('emailaddressesbody').appendChild(newDiv);
								
				Effect.BlindDown('notification' + newID);
							
			},
		    onFailure: function(){ 
				alert('Failed to add email address');
			}
		});	
		
	}
	
	function sendEmail() {
		
		from =  document.forms["mail"].from.value;
		body =  document.forms["mail"].body.value;
		subject = document.forms["mail"].subject.value;
		file = document.forms["mail"].file.value;
		
		new Ajax.Request('send',
		{
			method:'post',
			parameters: {from: from, subject: subject, body: body, file: file, time: new Date().getTime()},
			onSuccess: function(transport) {
				// Close the send email window
				hs.close(document.getElementById('highslide-html'));
				// Open success email window
			},
			onFailure: function() {
				alert('Failed to send email');
			} 
		});
		
	}
	
	function deleteNotification(id) {
		
		new Ajax.Request('delete?id=' + id + '&time=' + new Date().getTime(),
		{
			method:'get',
			onSuccess: function(transport) {
				Effect.Fade(document.getElementById('notification' + id));					
			},
		    onFailure: function(){ 
				Effect.Pulsate(document.getElementById('notification' + id));
				document.getElementById('notification' + id).innerHTML='Sorry, something went wrong. Please try again later.';
			}
		});
		
		
	}
	
	function echeck(str) {

			var at="@"
			var dot="."
			var lat=str.indexOf(at)
			var lstr=str.length
			var ldot=str.indexOf(dot)
			if (str.indexOf(at)==-1){
			   alert("Invalid E-mail ID")
			   return false
			}

			if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){
			   alert("Invalid E-mail ID")
			   return false
			}

			if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){
			    alert("Invalid E-mail ID")
			    return false
			}

			 if (str.indexOf(at,(lat+1))!=-1){
			    alert("Invalid E-mail ID")
			    return false
			 }

			 if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){
			    alert("Invalid E-mail ID")
			    return false
			 }

			 if (str.indexOf(dot,(lat+2))==-1){
			    alert("Invalid E-mail ID")
			    return false
			 }

			 if (str.indexOf(" ")!=-1){
			    alert("Invalid E-mail ID")
			    return false
			 }

	 		 return true					
		}


    function updateYoutubeVideo(id)    
    {       
        var html  = '';       
        html += '<object width="350" height="300">';       
        html += '<param name="movie" value="http://www.youtube.com/v/'+id+'&#038;rel=1&#038;fs=1&#038;showsearch=0&#038;hd=0"></param>';       
        html += '<param name="autoplay" value="1">';       
        html += '<param name="wmode" value="transparent"></param>';  
        html += '<param name="allowFullScreen" value="true"></param>';       
        html += '<embed src="http://www.youtube.com/v/'+id+'&#038;rel=1&#038;fs=1&#038;showsearch=0&#038;hd=0;autoplay=1;" type="application/x-shockwave-flash" wmode="transparent" allowfullscreen="true" width="350" height="300"></embed>';       
        html += '</object>';      

		document.getElementById('youtubePlayer').innerHTML = html;   
     };
     
     function updateYoutubeVideoMain(id)    
     {       
         var html  = '';       
         html += '<object width="550" height="400">';       
         html += '<param name="movie" value="http://www.youtube.com/v/'+id+'&#038;rel=1&#038;fs=1&#038;showsearch=0&#038;hd=0"></param>';       
         html += '<param name="autoplay" value="1">';       
         html += '<param name="wmode" value="transparent"></param>';  
         html += '<param name="allowFullScreen" value="true"></param>';       
         html += '<embed src="http://www.youtube.com/v/'+id+'&#038;rel=1&#038;fs=1&#038;showsearch=0&#038;hd=0;autoplay=1;" type="application/x-shockwave-flash" wmode="transparent" allowfullscreen="true" width="550" height="400"></embed>';       
         html += '</object>';      

 		document.getElementById('youtubePlayerMain').innerHTML = html;   
      };

     var swapit;
     function Animate(c) {
    	 var b,a,d=document.getElementById(c);
    	 d.src=(d.src.substr(0,b=d.src.lastIndexOf('/')+1)+
    	 ((a=d.src.substr(b++,1))==3?1:++a)+d.src.substring(b));
    	 swapit=window.setTimeout("Animate('"+c+"')",1000);
     };

     function DeAnimate() {
     	window.clearTimeout(swapit);
     };

     function populateScreen(id, title, description, thumbnail){

		document.getElementById('title').value = title;
		document.getElementById('videoId').value = id;
		document.getElementById('thumbnail').value = thumbnail;
		document.getElementById('fileLabel').style.display = 'none';
		document.getElementById('fileInput').style.display = 'none';
		FCKeditorAPI.GetInstance('description').SetHTML(description);
		
		hs.close('youtubePopup');
     };

	
	



function getTrackStats(id){
	new Ajax.Request('trackstats',
  	{
  		
	    method:'post',
	    onSuccess: function(transport){
	      var response = transport.responseText || "no response text";
	      $("trackStats").innerHTML = response;
	    },
    	onFailure: function(){ alert('Something went wrong...') },
    	parameters: {trackid: id }
  	});

}

function embedScreenshots(baseUrl){
	
	var newURL = window.location.protocol + "//" + window.location.host + "/" + baseUrl + "/screens.xml";

	var flashvars = {
		galleryUrl:newURL
	};

	var params = {
			menu: "false",
			scale: "noScale",
			allowFullscreen: "false",
			allowScriptAccess: "always",
			bgcolor: "#333333",
			wmode: "transparent"
	};
	var attributes = {
			id:"ScreenshotControl"
	};

	swfobject.embedSWF(baseUrl + "/flash/ScreenshotControl.swf", "altContentScreens", "584", "400", "9.0.0", baseUrl + "/flash/expressInstall.swf", flashvars, params, attributes);

}

function embedStats(baseUrl, playerId){
	
	var summaryURL = window.location.protocol + "//" + window.location.host + baseUrl + "/stats/summaryxml?id=";
	var newsURL = window.location.protocol + "//" + window.location.host + baseUrl + "/stats/newsxml?id=";
	var detailsURL = window.location.protocol + "//" + window.location.host + baseUrl + "/stats/detailsxml?id=";
	var trackStatsURL = window.location.protocol + "//" + window.location.host + baseUrl + "/stats/trackstatsxml?playerId=";
	var trackListURL = window.location.protocol + "//" + window.location.host + baseUrl + "/stats/tracklistxml";

	var flashvars = {
		summaryUrl:summaryURL,
		newsUrl:newsURL,
		detailsUrl:detailsURL,
		trackStatsUrl:trackStatsURL,
		trackListUrl:trackListURL,
		playerId:playerId
	};

	var params = {
			menu: "false",
			scale: "noScale",
			allowFullscreen: "false",
			allowScriptAccess: "always",
			bgcolor: "#333333",
			wmode: "transparent"
	};
	var attributes = {
			id:"StatsControl"
	};

	swfobject.embedSWF(baseUrl + "/flash/StatsBox.swf", "altContentStats", "584", "950", "9.0.0", baseUrl + "/flash/expressInstall.swf", flashvars, params, attributes);

}

function embedLibraryLogos(baseUrl){
	
	var newURL = window.location.protocol + "//" + window.location.host + "/" + baseUrl + "/libraries.xml";

	var flashvars = {
		galleryUrl:newURL
	};

	var params = {
			menu: "false",
			scale: "noScale",
			allowFullscreen: "false",
			allowScriptAccess: "always",
			bgcolor: "#333333",
			wmode: "transparent"
	};
	var attributes = {
			id:"LibraryLogosFlashControl"
	};

	swfobject.embedSWF(baseUrl + "/flash/SponsorSlideShow.swf", "altLibraryLogos", "134", "50", "9.0.0", baseUrl + "/flash/expressInstall.swf", flashvars, params, attributes);

}

function button_on ( imgId )
{
  if ( document.images )
  {
    butOn = eval ( imgId + "_on.src" );
    document.getElementById(imgId).src = butOn;
  }
}

function button_off ( imgId )
{
  if ( document.images )
  {
    butOff = eval ( imgId + "_off.src" );
    document.getElementById(imgId).src = butOff;
  }
}

