// JavaScript Document
$(document).ready(function(){
	$('div#fileinfo').hide();
			//
	$("form[class!='noajax']").submit(function(){

		var divname = $('#submit').attr('rel');
		if(divname=="addproj1"){
			document.getElementById("addproj1").style.backgroundcolor='#99FF00'; 
			$('#aloader').empty().append('Saving...');
		}
		if(divname=="editteam"){
			document.getElementById("editteam").style.backgroundcolor='#99FF00'; 
			$('#aloader').empty().append('Saving...');
		}
		if(divname=="forgot"){
			document.getElementById("forgot").style.backgroundcolor='#99FF00'; 
			$('#aloader').empty().append('Processing...');
		}

		var divname2 = $('#submit2').attr('rel');
		if(divname2=="addproj2"){
			document.getElementById("addproj2").style.backgroundcolor='#99FF00'; 
			$('#aloader2').empty().append('Saving...');
		}

		var divname = $('#submit').attr('rel');
		if(divname=="adduser"){
			document.getElementById("adduser").style.backgroundcolor='#99FF00'; 
			$('#aloader').empty().append('Saving...');
		}

		var divname2 = $('#submit2').attr('rel');
		if(divname2=="edituser"){
			document.getElementById("edituser").style.backgroundcolor='#99FF00'; 
			$('#aloader2').empty().append('Saving...');
		}

		var divname3 = $('#submit3').attr('rel');
		if(divname3=="deleteuser"){
			document.getElementById("deleteuser").style.backgroundcolor='#99FF00'; 
			$('#aloader3').empty().append('Deleting...');
		}
							  
		//$('#SCloading').empty().append('<img src="images/ajaxloader1.gif" width="50" height="50" border="0" alt="Loading.." />').fadeIn('fast');
		
		tinyMCE.triggerSave();
		
		// do some javascript validation here if you want		
		
		var s = $(this).serialize();
		var theform = $(this).attr('name');
		var getdata = true;		
		
		// check if it's a delete form, if so do a double check first before 
		// doing the ajax bit.
		if (theform.indexOf('delete') != -1){		
			if (confirm('Are you sure you want to delete this, it will be gone forever?')){
				getdata = true;	
			} else {
				getdata = false;	
			}		
		}
		
		
		
		if (getdata){
			$.ajax({
				url: 'php_functions/jobs.php',
				type: 'POST',
				dataType: 'xml',
				data: s,
				timeout: 9000,
				success: function(xml){
					// do something with xml
					if($('status', xml).text() == 'success'){						

						
						if(divname=="addproj1")
						{
							var cc = new ColorChanger("addproj1", "backgroundColor", "99FF00");
							cc.ChangeColor("CCCCCC", 50, 65);
							var bb = new ColorChanger("aloader", "color", "000000");
							bb.ChangeColor("CCCCCC", 50, 65);
						}

						if(divname=="editteam")
						{
							var cc = new ColorChanger("editteam", "backgroundColor", "99FF00");
							cc.ChangeColor("CCCCCC", 50, 65);
							var bb = new ColorChanger("aloader", "color", "000000");
							bb.ChangeColor("CCCCCC", 50, 65);
						}

						if(divname=="forgot")
						{
							var cc = new ColorChanger("forgot", "backgroundColor", "99FF00");
							cc.ChangeColor("CCCCCC", 50, 65);
							var bb = new ColorChanger("aloader", "color", "000000");
							bb.ChangeColor("CCCCCC", 50, 65);
						}

						if(divname2=="addproj2")
						{
							var cc = new ColorChanger("addproj2", "backgroundColor", "99FF00");
							cc.ChangeColor("CCCCCC", 50, 65);
							var bb = new ColorChanger("aloader2", "color", "000000");
							bb.ChangeColor("CCCCCC", 50, 65);
						}

						if(divname=="adduser")
						{
							var cc = new ColorChanger("adduser", "backgroundColor", "99FF00");
							cc.ChangeColor("CCCCCC", 50, 65);
							var bb = new ColorChanger("aloader", "color", "000000");
							bb.ChangeColor("CCCCCC", 50, 65);
						}

						if(divname2=="edituser")
						{
							var cc = new ColorChanger("edituser", "backgroundColor", "99FF00");
							cc.ChangeColor("CCCCCC", 50, 65);
							var bb = new ColorChanger("aloader2", "color", "000000");
							bb.ChangeColor("CCCCCC", 50, 65);
						}

						if(divname3=="deleteuser")
						{
							var cc = new ColorChanger("deleteuser", "backgroundColor", "99FF00");
							cc.ChangeColor("CCCCCC", 50, 65);
							var bb = new ColorChanger("aloader3", "color", "000000");
							bb.ChangeColor("CCCCCC", 50, 65);
						}
						
						
						
						// refresh any lists
						$('select.updatelist').each(function(){
							refreshlist($(this).attr('id'), $(this).attr('rel'));										
						});
						
						// clear form
						if ($('team', xml).text()!='details')
						{
							$('#title').empty();
							$('#body').empty();
							$('#title2').empty();
							$('#body2').empty();
							$('form').find('input:text').val('');
							$('form').find('input:password').val('');
							$('form').find('select').val('');
							$('form').find('textarea:not(textarea.SCwysiwyg)').val('');
							$('form').find('textarea.SCwysiwyg').each(function(){
								var ed = tinyMCE.getInstanceById($(this).attr('id'));
								ed.setContent('');
							});
						}

						
					} else {

						
						if(divname2=="addproj2")
						{
							$('#aloader2').empty().append($('message', xml).text());
							var cc = new ColorChanger("addproj2", "backgroundColor", "CB0101");
							cc.ChangeColor("CCCCCC", 50, 65);
							var bb = new ColorChanger("aloader2", "color", "000000");
							bb.ChangeColor("CCCCCC", 50, 65);
						}

						if(divname=="adduser")
						{
							$('#aloader').empty().append($('message', xml).text());
							var cc = new ColorChanger("adduser", "backgroundColor", "CB0101");
							cc.ChangeColor("CCCCCC", 50, 65);
							var bb = new ColorChanger("aloader", "color", "000000");
							bb.ChangeColor("CCCCCC", 50, 65);
						}

						if(divname=="forgot")
						{
							$('#aloader').empty().append($('message', xml).text());
							var cc = new ColorChanger("forgot", "backgroundColor", "CB0101");
							cc.ChangeColor("CCCCCC", 50, 65);
							var bb = new ColorChanger("aloader", "color", "000000");
							bb.ChangeColor("CCCCCC", 50, 65);
						}

						if(divname=="editteam")
						{
							$('#aloader').empty().append($('message', xml).text());
							var cc = new ColorChanger("editteam", "backgroundColor", "CB0101");
							cc.ChangeColor("CCCCCC", 50, 65);
							var bb = new ColorChanger("aloader", "color", "000000");
							bb.ChangeColor("CCCCCC", 50, 65);
						}

						if(divname2=="edituser")
						{
							$('#aloader2').empty().append($('message', xml).text());
							var cc = new ColorChanger("edituser", "backgroundColor", "CB0101");
							cc.ChangeColor("CCCCCC", 50, 65);
							var bb = new ColorChanger("aloader2", "color", "000000");
							bb.ChangeColor("CCCCCC", 50, 65);
						}

						if(divname3=="deleteuser")
						{
							$('#aloader3').empty().append($('message', xml).text());
							var cc = new ColorChanger("deleteuser", "backgroundColor", "CB0101");
							cc.ChangeColor("CCCCCC", 50, 65);
							var bb = new ColorChanger("aloader3", "color", "000000");
							bb.ChangeColor("CCCCCC", 50, 65);
						}
					}
				}
				
			});			
								
		}
		
		return false;
		
	});
	
	$('a.tab').click(function(){
	
		var tab = $(this).attr('id');		
		$('div.tabdiv:visible').hide();		
		$('a.tab').removeClass('tabon');		
		$('div#'+tab+'tab').show();		
		$('a#'+tab).addClass('tabon');		
		return false;
	
	});
	
	$('select.editlist').change(function(){
										 
		$('#SCloading').empty().append('<img src="images/ajaxloader1.gif" width="50" height="50" border="0" alt="Loading.." />').fadeIn('fast'); 
										 
		// this will get the data for that item and display it
		
		var listdata = $(this).attr('rel');
		var dataid = $(this).val();
		
		$.ajax({
			url: 'php_functions/jobs.php',
			type: 'POST',
			dataType: 'xml',
			data: {'adminmode':'getlist','listdata':listdata,'id':dataid},
			timeout: 9000,
			error: function(){
				$('#SCloading').empty().append('<p><strong>Error:</strong><br />Error loading XML document</p>');
			},
			success: function(xml){
				// do something with xml
				if($('status', xml).text() == 'success'){					
					$('#SCloading').fadeOut("fast");
					// populate form
					$('formfield',xml).each(function(){
						f = $(this).attr('name');
						t = $(this).text();
						e = '#'+f+'edit';
						switch ($(this).attr('type')){
							case 'text':								
								$("form[name='"+listdata+"edit']").find(e).val(t);
								break;
							case 'textarea':
								if ($(this).attr('ishtml') == 'y'){
									var ed = tinyMCE.getInstanceById(f+'edit');
									ed.setContent(t);
								} else {
									$("form[name='"+listdata+"edit']").find(e).val(t);	
								}
								break;
							case 'checkbox':
								if (t == 1){
									$("form[name='"+listdata+"edit']").find(e).attr('checked','checked');
								} else {
									$("form[name='"+listdata+"edit']").find(e).attr('checked','');
								}
								break;
							case 'select':
								$("form[name='"+listdata+"edit']").find(e).val(t);
								break;
						}						
					});	
					$('#SCloading').animate({opacity: 1.0}, 3000);
					$('#SCloading').fadeOut('slow');
				} else {
					$('#SCloading').empty().append('<p><strong>Error:</strong><br />'+$('message', xml).text()+'</p>');
				}
			}
		});	
	});
	
	
	
	
	
	$('.closebox').click(function(){
		$(this).parent().fadeOut('fast');	
		return false;
	});
	$('.cancelbutton').click(function(){
		$('#'+$(this).attr('rel')).fadeOut('fast');	
		return false;									 
	});
	

	
});

function setChangeParent(){
	$('.changeparentlink').click(function(e){
		$("#removesection:visible").fadeOut('fast');
		var s = $(this).attr('rel');
		var ss = s.split('|');
		var sectionid = ss[0];
		var parentid = ss[1];
			
		/* CONFIG */		
		xOffset = -180;
		yOffset = 20;		
		$("#changeparent")
			.css("top",(e.pageY - yOffset) + "px")
			.css("left",(e.pageX + xOffset) + "px")
			.fadeIn("fast");	
		$('#sectionnewparent').val(parentid);
		$('#structureid').val(sectionid);
		return false;
	});
	$('.removenodelink').click(function(e){
		$("#changeparent:visible").fadeOut('fast');
		var sectionid = $(this).attr('rel');
			
		/* CONFIG */		
		xOffset = -270;
		yOffset = 20;		
		$("#removesection")
			.css("top",(e.pageY - yOffset) + "px")
			.css("left",(e.pageX + xOffset) + "px")
			.fadeIn("fast");	
		$('#rstructureid').val(sectionid);
		return false;
	});
}


// javascript functions
function refreshlist(listid, list){
	if (listid != ''){				
		
		$.ajax({
			url: 'php_functions/jobs.php',
			type: 'POST',
			dataType: 'xml',
			data: {'adminmode':'refreshlist','list':list},
			timeout: 9000,
			error: function(){
				//$('#SCloading').empty().append('<p><strong>Error:</strong><br />Error loading XML document, cannot refresh list.</p>');
			},
			success: function(xml){
				$('select#'+listid).empty();
				$('optionfield',xml).each(function(){
					var id = $(this).attr('id');
					var depth = $(this).attr('depth');
					var gap = '';
					for(i=1;i<=depth;i++){
						gap += '&nbsp;&nbsp;';	
					}
					var txt = gap+$(this).text();		
					var css = '';
					if ($(this).attr('class') != ''){
						css = ' class="'+	$(this).attr('class') +'"';
					} else {
						css = '';	
					}
					$('select#'+listid).append('<option value="'+id+'"'+css+'>'+txt+'</option>');
				});			
			}
		});		
	}
}


$('a#delete').click(function(){
		
		// do some javascript validation here if you want

		var mediaid = $(this).attr('rel');
		
		$.ajax({
			url: 'php_functions/jobs.php',
			type: 'POST',
			dataType: 'xml',
			data: {'adminmode':'delete','mediaid':mediaid},
			timeout: 9000,
			error: function(){
				$('#SCloading').empty().append('<p><strong>Error:</strong><br />Error loading XML document</p>');
			},
			success: function(xml){
				// do something with xml
				if($('status', xml).text() == 'success'){					
					$('#SCloading').empty().append('<p><strong>Success:</strong><br />Media was successfully removed from the system</p>');		
					$('div.'+mediaid+'').hide();
					$('div#fileinfo').hide();
					$('div#mm').show();
					$('#SCloading').animate({opacity: 1.0}, 3000);
					$('#SCloading').fadeOut('slow');
				} else {
					$('#SCloading').empty().append('<p><strong>Error:</strong><br />'+$('message', xml).text()+'</p>');
				}
			}
		});
		return false;
	});


	$('select.medialist').change(function(){	 
										 
		// this will get the data for that item and display it
		
		var listdata = $(this).attr('rel');
		var dataid = $(this).val();

		//$('div.themainclass').hide();
		$('div.doc').hide();
		$('div.xls').hide();
		$('div.image').hide();
		$('div.ppt').hide();
		$('div.pdf').hide();
		$('div.flv').hide();
		$('div#mediadetails').hide();
		$('.thumbnail').removeClass('highlight');
		if (dataid == 'all'){
			$('div.doc').show();
			$('div.xls').show();
			$('div.image').show();
			$('div.ppt').show();
			$('div.pdf').show();
			$('div.flv').show();
		} else{
			$('div.'+dataid+'').show();
		}   
	});


	// Should be used for drop down selection in media manager 
	$('select.medialist_uploaded').change(function(){	 
										 
		// this will get the data for that item and display it
		
		var listdata = $(this).attr('rel');
		var dataid = $(this).val();

		//$('div.themainclass').hide();
		$('div.ancient').hide();
		$('div.day').hide();
		$('div.3days').hide();
		$('div.week').hide();
		$('div.month').hide();
		$('div#mediadetails').hide();
		$('.thumbnail').removeClass('highlight');
		if (dataid == 'ancient'){
			$('div.ancient').show();
			$('div.day').show();
			$('div.3days').show();
			$('div.week').show();
			$('div.month').show();
		} 
		if (dataid == 'month'){
			$('div.day').show();
			$('div.3days').show();
			$('div.week').show();
			$('div.month').show();
		}
		if (dataid == 'week'){
			$('div.day').show();
			$('div.3days').show();
			$('div.week').show();
		} 
		if (dataid == '3days'){
			$('div.day').show();
			$('div.3days').show();
		} 
		if (dataid == 'day'){
			$('div.day').show();
		} 
	});

	$('p.close').click(function(){	 
		$('div#fileinfo').hide();
		$('div#mm').show();
		
	});


	// The code for populating the popup boxes in file manager
	$('.edit').click(function(e){
		var offset = $(this).offset();
		e.stopPropagation();
		var p = $(this).attr('rel');
					
		/*$("#mediadetails")
			.css("top",(offset.top +25) + "px")
			.css("left",(offset.left -75) + "px")
			.fadeIn("slow");
		$('.thumbnail').removeClass('highlight');
		$(this).parent().addClass('highlight');*/
		$('div#mm').hide();
		$('div#fileinfo').show();
		
		
		$.ajax({
			url: 'php_functions/jobs.php',
			type: 'POST',
			dataType: 'xml',
			data:{'adminmode':'getfiledetails','fileid':p},
			timeout: 9000,
			error: function(){
				$('#SCloading').empty().append('<p><strong>Error:</strong><br />Error loading XML document</p>');
			},
			success: function(xml){
				// do something with xml
				if($('status', xml).text() == 'success'){					
					// populate form
				
					$('#filename').val($('filename',xml).text());
					//$('#tags').val($('filetags',xml).text());
					$('div#url').empty().append($('fileurl',xml).text());
					$('#description').val($('filedesc',xml).text());
					$('div#author').empty().append($('fileauthor',xml).text());
					$('div#date').empty().append($('filedate',xml).text());
					$('a#delete').attr('rel',p);
					$('div#download').empty().append('<a href="'+$('plainurl',xml).text()+'">'+'<img src="images/media_download.jpg" title="download file (right click >> save target as)" />'+'</a>');
					if ($('imgurl',xml).text() != '')
					{
						$('div#image').empty().append('<img src="'+$('imgurl',xml).text()+'"/>');
					}else{
						$('div#image').empty();
					}
					
					//<img src="sunset.gif" />

					$('#mediaid').attr('value',p);
					$('#SCloading').animate({opacity: 1.0}, 3000);
					$('#SCloading').fadeOut('slow');
				} else {
					$('#SCloading').empty().append('<p><strong>Error:</strong><br />'+$('message', xml).text()+'</p>');
				}
			}
		});
		return false;
	});












	function ColorChanger(elemId, property, currColor) {
	this.elemId = elemId;
	this.property = property;
	this.currColor = currColor;
}

ColorChanger.prototype.elemId = null;
ColorChanger.prototype.property = null;
ColorChanger.prototype.currColor = null;
ColorChanger.prototype.currChange = null;

ColorChanger.prototype.ChangeColor = function(newColor, frames, frameDelay) { 
	clearTimeout(this.currChange);
	var stepsR = this.CreateSteps(this.ConvertHexToBinary(this.currColor.substr(0,2)), this.ConvertHexToBinary(newColor.substr(0,2)), frames);
	var stepsG = this.CreateSteps(this.ConvertHexToBinary(this.currColor.substr(2,2)), this.ConvertHexToBinary(newColor.substr(2,2)), frames);
	var stepsB = this.CreateSteps(this.ConvertHexToBinary(this.currColor.substr(4,2)), this.ConvertHexToBinary(newColor.substr(4,2)), frames);
	this.ChangeColorStep(newColor, frames, frameDelay, stepsR, stepsG, stepsB);
}

ColorChanger.prototype.ChangeColorStep = function(newColor, frames, frameDelay, stepsR, stepsG, stepsB) { 
	this.currColor = (frames == 1) ? newColor : stepsR[frames-1] + stepsG[frames-1] + stepsB[frames-1];
	eval("document.getElementById('" + this.elemId + "').style." + this.property + "='#" + this.currColor + "';");
	if (frames > 1) { 
		var closureThis = this;
		this.currChange = setTimeout(function(){closureThis.ChangeColorStep(newColor, frames-1, frameDelay, stepsR, stepsG, stepsB); closureThis = null;}, frameDelay);
	}
}

ColorChanger.prototype.CreateSteps = function(startVal, endVal, frames) { 
	var ret = new Array();
	for (var f=frames-1; f >= 0; f--)
		ret[f] = this.ConvertBinaryToHex(Math.ceil(startVal + (((endVal - startVal) / frames)) * (frames - f - 1)), 2);
	return ret;
}

// based on this: http://snipplr.com/view/139/base-conversion/
ColorChanger.prototype.ConvertBinaryToHex = function(dec, padding) { 
	var base = "0123456789ABCDEF";
	var len = base.length;
	var ret = '';
	while(dec > 0) {
		ret = base.charAt(dec % len) + ret;
		dec = Math.floor(dec / len);
	}
	while(ret.length < padding) ret = "0" + ret;
	return ret;
}

ColorChanger.prototype.ConvertHexToBinary = function(num) { 
	var base = "0123456789ABCDEF";
	var len = base.length;
	var ret = 0;
	for(var x=1; num.length > 0; x *= len) {
		ret += base.indexOf(num.charAt(num.length - 1)) * x;
		num = num.substr(0,num.length - 1);
	}
	//$('#aloader').empty();
	return ret;
}
