/**
 * Adds the events to each of the arrows in the newsArchive section (hides the buttons in the job form)
 * @date 1/14/2010
 * @author davo
 * 
 */
document.observe("dom:loaded", function() {	
	$$('.toggleArrow').each(function(element){
		element.next('.newsul').toggle();
		element.toggleClassName('arwr');
		element.observe('click',respondToClick);
	});
	$$('.month').each(function(element){
		element.observe('click',respondToClickMonth);
	});
	$$('.jobBtn').each(function(element){
		if(element.id != 'jobSubmit')
			element.toggle();
	});
	$$('.newsBtn').each(function(element){
		if(element.id != 'newsSubmit')
			element.toggle();
	});
	if($('newsidfield'))
	{	
		$('newsidfield').value != ''? setButtons('newsEdit'): 0 ;
	}
	if($('jobidfield'))
	{
		$('jobidfield').value != ''? setButtons('jobEdit'): 0;
	}
	if($('textContent'))
	{
		makeEd('textContent');
	}
	$$('.disable').each(function(element){
		element.disable();
	});
	
});

/**
 * This will just trigger the toggling of the  arrow images in the newsArchive arrows.
 * @date 1/15/2010
 * @author davo
 * @param event contains the triggered arrow
 * @return update image
 */
function respondToClick(event) {
	var evente = event.element();
	var element = evente.next('.newsul'); 
	element.toggle();
	evente.toggleClassName('arwu');
	evente.toggleClassName('arwr');
}

function respondToClickMonth(event) {
	var evente = event.element();
	var element = evente.next('.newsul');
	element.toggle();
	
	var arr = evente.previous('.toggleArrow');
	arr.toggleClassName('arwr');
	arr.toggleClassName('arwu');
}

/**
 * Taken from Tweetbets /js/bets.js, it verifies if the content in a text input is numeric or backspace (allows tab now).
 * @date 1/18/2010
 * @author davo (brambs @ /js/bets.js)
 * @param e triggered event and its elements
 * @return boolean, true for successful verification, false for non-numerical input
 */
function isNumeric(e) {
    e = (e) ? e : window.event;
    var charCode = (e.which) ? e.which : e.keyCode;
    //48-57: top numbers, 96-105: numpad numbers, 8: backspace, 9: tab, 190: qwerty dot, 110 = numpad dot. 
    if((charCode < 48 || charCode > 57) && (charCode < 96 || charCode > 105) && charCode != 8 && charCode != 9 && charCode != 190 && charCode!= 110){
        return false;
    }
    return true;
}

/**
 * @date 1/20/2010
 * @author davo
 * @return 
 */
function statsUpdate()
{
	var siteSelect = $('siteSelect');
	var siteValue = siteSelect.options[siteSelect.selectedIndex].value;
	if(siteValue == 0){
		alert('Select a site to edit the stats.');
		siteSelect.focus();
		return;
	}
	var cont = true;
	var fields = $$('.max100');
	fields.each(function(element){
		var value = element.value;
		var alert = element.next(0);
		if(value == parseFloat(value)){
			if(value > 100){
				cont = false;
				if(!alert){
					element.ancestors()[0].insert('<label class="alert clrred t12"> the value must not exceed 100% </label>');
				}
				else
					alert.update('The value must not exceed 100% ');
			}else{
				if(alert){
					alert.remove();
				}
			}
		}else{
			if(value != ""){
				cont = false;
				if(!alert){
					element.ancestors()[0].insert('<label class="alert clrred t12"> this field contains invalid values </label>');
				}
				else
					alert.update('this field contains invalid values');
			}
		}
	});
	
	if(cont){	
		$('statsForm').request({		
			onSuccess: function(re){
				$('updateStatus').update('Stats were updated succesfully.');
				clear_stats_form_fields();
				new PeriodicalExecuter(function(pe) {
					  	$('updateStatus').innerHTML = '';
					    pe.stop();
					}, 5);

			},
			onFailure: function(re){
				$('updateStatus').update('There was an error trying to update the stats, please try again.');
			}
		});
	}else{
		$('updateStatus').update('There are errors in the form, please verify the input');
	}
}

function clear_stats_form_fields()
{
	$('nationSelector').value = 0;
	$$('.disable').each(function(element){
		if(element.value != "Add Country")
			element.clear();
		element.disable();
	});
	$('nationsTable').hide();
	$('siteSelect').value = 0;
	$$('.alert').each(function(element){
		element.innerHTML='';
	});
}

/**
 * @date 1/20/2010
 * @author Eric
 * @return
 */
function news_Submit(){	
	var submit = false;
	if($('input_title').value==''){
		alert('Please write the article header.');
		$('input_title').focus();
		return;
	}
	if($('input_info').value==''){
		alert('Please write the article info.');
		$('input_info').focus();
		return;
	}
	if($('input_image').value=='' && ($('cbHome').checked || $('cbIndex').checked)){
		alert('Please select an image (max. 300px width).');
		$('input_image').focus();
		return;
	}
	if($('textContent').value==''){
		alert('The article content can\'t be left in blank. Please write the content.');
		$('textContent').focus();
		return;
	}
	$('newsForm')['formType'].value='newsForm';
	$('newsForm').submit();
}

/**
 * Based on the same structure as newsSubmit, this will attempt to submit an opening job.
 * @date 1/22/2010
 * @author davo
 * @param Post parameters from jobsForm
 * @return
 */
function job_Submit()
{
	$('jobsForm').submit();
}

/**
 * Attempts to load the selected job in the jobs'select element from the DB.
 * @author davo
 * @param ID int job's id to retrieve.
 * @return array job's info
 */
function getJobInfo(id)
{
	$('jobsForm').reset();
	if(id == 0)
	{
		setButtons('jobSubmit');
		$('jobsForm')['Content'].value = '';
		return;
	}
	url="/content/admin.scripts.php";
	new Ajax.Request( 
		url, 
		{
			method: 'get', 
			parameters: {formType:'getJob', ID: id},
			onSuccess: function(e){
				var form = $('jobsForm');
				var prueba = JSON.parse(e.responseText );
				form['Content'].update(prueba.Content);
				form['Title'].value = prueba.Title;
				if(prueba.Lang == "en")
				{
					form['langen'].checked = true;
				}
				else
				{
					form['langes'].checked = true;
				}
				setButtons('jobEdit');
			}
		});
}

/**
 * This method searches for the selected News and loads the news' content into the form
 * @author davo
 * @param id news'id to search content for  (if 0, it will clear the form for a new news)
 */
function getNewsInfo(id)
{
	$('newsForm').reset();
	$('newsForm')['NewsSelect'].value = id;
	if(id == 0)
	{
		setButtons('newsSubmit');	
		$('newsForm')['Content'].value = '';
		$('newsForm')['Info'].value = '';
		return;
	}
	url="/content/admin.scripts.php";
	new Ajax.Request( 
		url, 
		{
			method: 'get', 
			parameters: {formType:'getNews', ID: id},
			onSuccess: function(e){
				var form = $('newsForm');
				var prueba = JSON.parse(e.responseText );
				form['Info'].update(prueba.Info);
				form['Content'].update(prueba.Content);
				form['Title'].value = prueba.Title;
				form['Keywords'].value = prueba.Keywords;
				form['Websites'].value = prueba.Websites;
				
				//1 = index, 2 = home, 3=both
				if(prueba.Featured == 1 || prueba.Featured == 3)
				{
					form['cbIndex'].checked = true;
				}
				if(prueba.Featured== 2 || prueba.Featured == 3)
				{
					form['cbHome'].checked = true;
				}
				if(prueba.Lang == "en")
				{
					form['langen'].checked = true;
				}
				else
				{
					form['langes'].checked = true;
				}
				setButtons('newsEdit');
			}
		});
}

/**
 * 
 * 2/15/2010
 * @author davo
 * @param id int ID of the job to hide
 * @param domain string the domain name to build the redirect link
 * @param lang string language of the selected job. 
 * @return
 */
function hidenews(id,domain,lang)
{
	url="/content/admin.scripts.php";
	
	var proc = confirm("Are you sure you want to erase the selected news?");
	if(proc == true)
	{
		new Ajax.Request( 
				url, 
					{
						method: 'get', 
						parameters: {formType:'newsremove', ID: id },
						onSuccess: function(e){
							e;
							alert('news removed :D');
							location.href = "http://"+domain+"/"+ lang +"/news/";
					},
						onFailure: function(e){
						alert(e.status);
					}
				});
	}
}

/**
 * 1/27/2010
 * Function that will Confirm the remove action, and then attempt to remove the desired news
 * @author davo
 */
function news_Remove()
{
	var proc = confirm("Are you sure you want to erase the selected news?");
	if(proc == true)
	{
		$('newsForm')['formType'].value='newsremove';
		$('newsForm').submit();
	}
}

/**
 * 1/27/2010
 * Edits the information according to the new input
 * @author davo
 */
function news_Edit()
{
	var proc = confirm("Are you sure you want to submit the changes?");
	$('newsForm')['formType'].value='newsedit'; 
	if(proc == true)
	{
		if($('input_title').value==''){
			alert('Please write the article header.');
			$('input_title').focus();
			return;
		}
		if($('input_info').value==''){
			alert('Please write the article info.');
			$('input_info').focus();
			return;
		}
		if($('input_image').value=='' && ($('cbHome').checked || $('cbIndex').checked) && ($('uploadedimg').value == 'default.jpg' || $('uploadedimg').value == '')){
			alert('Please select an image (max. 300px width min. 50 width and height).');
			$('input_image').focus();
			return;
		}
		if($('textContent').value==''){
			alert('The article content can\'t be left in blank. Please write the content.');
			$('textContent').focus();
			return;
		}
		$('newsForm').submit();
	}
}

/**
 * 2/15/2010
 * @author davo
 * @param id int ID of the job to hide
 * @param domain string the domain name to build the redirect link
 * @param lang string language of the selected job. 
 * @return
 */
function hidejob(id,domain,lang)
{
	url="/content/admin.scripts.php";
	var proc = confirm("Are you sure you want to remove the selected job?");
	if(proc == true)
	{
		new Ajax.Request( 
				url, 
					{
						method: 'get', 
						parameters: {formType:'remJob', ID: id },
						onSuccess: function(e){
							e;
							alert('job removed :D');
							location.href = "http://"+domain+"/"+ lang +"/careers/";
					},
						onFailure: function(e){
						alert(e.status);
					}
				});
	}
	
}

/**
 * 1/26/2010
 * Edits the information according to the new input
 * @author davo
 */
function job_Edit()
{
var form = $('jobsForm');
url="/content/admin.scripts.php";
var proc = confirm("Are you sure you want to submit the changes?");
if(proc == true)
{
	$('jobsForm')['formType'].value = 'updJob';
	$('jobsForm').submit();
}
}
/**
 * Disable enter key on forms
 * @param e keyevent
 * @return bool If pressed key is 'enter'
 */
function disableEnterKey(e)
{
     var key;     
     if(window.event)
          key = window.event.keyCode; //IE
     else
          key = e.which; //firefox     

     return (key != 13);
}

/**
 * Toggles the different buttons in the site
 * @author davo
 * @param id
 */
function setButtons(id)
{
	
	$$('.jobBtn').each(function(e){
		e.hide();
	});
	$$('.newsBtn').each(function(e){
		e.hide();
	});
	$(id).show();

}

function edTag(el,tag,param){
	var selText = '';
	var newText = '';
	if (el.setSelectionRange){
		selText = el.value.substring(el.selectionStart,el.selectionEnd);
	}else{
		selText = document.selection.createRange().text;
	}
	switch(tag){
		case 'levelup':
		case 'youtube':
			if (selText!=''){
				if(selText.substring(0,7)=='http://'){
					newText = '['+tag+']'+selText+'[/'+tag+']';
				}else{
					var url = prompt('Ingrese el URL', 'Ingrese el URL');
					if(url != null){
						newText = selText+' ['+tag+']'+url+'[/'+tag+']';
					}
				}
			}else{
				var url = prompt('Ingrese el URL', 'Ingrese el URL');
				if(url != null){
					newText = '['+tag+']'+url+'[/'+tag+']';
				}
			}
			break;
		case 'url':
			if (selText!=''){
				if(selText.substring(0,7)=='http://'){
					newText = '[url='+selText+']'+selText+'[/url]';
				}else{
					var url = prompt('Ingrese el URL', 'Ingrese el URL');
					if(url != null){
						newText = '[url='+url+']'+selText+'[/url]';
					}
				}
			}else{
				var url = prompt('Ingrese el URL', 'Ingrese el URL');
				if(url != null){
					newText = '[url='+url+']'+url+'[/url]';
				}
			}
			break;
		case 'img':
			if (selText!=''){
				if(selText.substring(0,7)=='http://' || selText.substring(0,8)=='https://' || selText.substring(0,6)=='ftp://'){
					newText = '[img]'+selText+'[/img]';
				}else{
					var url = prompt('Ingrese el URL', 'Ingrese el URL');
					if(url != null){
						newText = selText+' [img]'+url+'[/img]';
					}
				}
	       }else{
	            var url = prompt('Ingrese el URL', 'Ingrese el URL');
	            if(url != null){
	                 newText = '[img]'+url+'[/img]';
	            }
	       }
	       break;
	  default:
	       if (param){
	            newText = '['+tag+'='+param+']'+selText+'[/'+tag+']';
	       }else{
	            newText = '['+tag+']'+selText+'[/'+tag+']';
	       }
	       break;
	}
	if (newText != '') {
		if (el.setSelectionRange){
			el.value = el.value.substring(0,el.selectionStart) + newText + el.value.substring(el.selectionEnd,el.value.length);
		}else{
			document.selection.createRange().text = newText;
		}
	}
	return false;
}

function makeEd(name){
	var editor = $(name);
	var ul = $c('ul');
	ul.className = 'edHdr';
	ul.innerHTML = '<li><a href="#" onclick="edTag($(\''+name+'\'),\'b\');return false;" class="edB" title="Bold"></a></li>';
	ul.innerHTML += '<li><a href="#" onclick="edTag($(\''+name+'\'),\'i\');return false;" class="edI" title="Italic"></a></li>';
	ul.innerHTML += '<li><a href="#" onclick="edTag($(\''+name+'\'),\'u\');return false;" class="edU" title="Underline"></a></li>';
	ul.innerHTML += '<li><span class="edSep"></span></li>';
	ul.innerHTML += '<li><a href="#" onclick="edTag($(\''+name+'\'),\'center\');return false;" class="edC" title="Texto centrado"></a></li>';
	ul.innerHTML += '<li><span class="edSep"></span></li>';
	ul.innerHTML += '<li><a href="#" onclick="edTag($(\''+name+'\'),\'levelup\');return false;" class="edLU" title="Video de LevelUp"></a></li>';
	ul.innerHTML += '<li><a href="#" onclick="edTag($(\''+name+'\'),\'img\');return false;" class="edIMG" title="Insertar Imßgen"></a></li>';
	ul.innerHTML += '<li><a href="#" onclick="edTag($(\''+name+'\'),\'url\');return false;" class="edURL" title="Insertar URL"></a></li>';
	editor.parentNode.insertBefore(ul,editor);
}

function insertEdText(el,text){
	if (text != '') {
		if (el.setSelectionRange){
			el.value = el.value.substring(0,el.selectionEnd) + text + el.value.substring(el.selectionEnd,el.value.length);
		}else{
			el.focus();
			selText = document.selection.createRange().text;
			document.selection.createRange().text = selText+text;
		}
	}
	return false;
}

function $c(string) { return document.createElement(string);};

function upload_result(result){
	if(result.status){
		$('lResults').update(result.msg);
		location.href = result.redirect;
	}
	else 
	{
		$('lResults').update(result.error);
	}
}

function setCookie(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+"="+escape(value)+"; path=/; domain="+DOMAIN_COOKIE+expires;
}

function clearCookie(name) {
	var cookie = name+"=; path=/; domain="+DOMAIN_COOKIE+"; expires=Thu, 01-Jan-1970 00:00:01 GMT";
	document.cookie = cookie;
}

function getCookie(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 uploadedImages(re){
	var div = document.createElement('div');
	div.className = 'loaded_image';
	div.innerHTML = re.html;
	if(!$('fieldset_images_loaded')){
		var divC = document.createElement('div');
		divC.id="fieldset_images_loaded";
		$('uploaded_images_div').appendChild(divC);
		divC.appendChild(div);
	}else $('fieldset_images_loaded').appendChild(div); 	
}

function insertUploadedImageTag(thumbnail){
	var imgTag = '[img]'+thumbnail+'[/img]';
	insertEdText($('textContent'),imgTag);
}
function roundNumber(rnum, rlength){
	return Math.round(rnum*Math.pow(10,rlength))/Math.pow(10,rlength);
}
