/**
 * 
 */
$(function(){
	String.prototype.trim = function() {
		return this.replace(/^\s+|\s+$/g, "");
	}
	String.prototype.ltrim = function() {
		return this.replace(/^\s+/, "");
	}
	String.prototype.rtrim = function() {
		return this.replace(/\s+$/, "");
	}
	
	$("a.anchor").anchorAnimate();
	if(document.location.hash.length < 1) {
		$("a.home.anchor").click();
	}
	
	//change the main div to overflow-hidden as we can use the slider now
	$('#scroll-pane').css('overflow','hidden');

	//compare the height of the scroll content to the scroll pane to see if we need a scrollbar
	var difference = $('#scroll-content').height()-$('#scroll-pane').height();//eg it's 200px longer

	if(difference>0){
		var proportion = difference / $('#scroll-content').height();//eg 200px/500px
		var handleHeight = Math.round((1-proportion)*$('#scroll-pane').height());//set the proportional height - round it to make sure everything adds up correctly later on
		handleHeight -= handleHeight%2;

		$("#scroll-pane").after('<\div id="slider-wrap"><\div id="slider-vertical"><\/div><\/div>');//append the necessary divs so they're only there if needed
		$("#slider-wrap").height($("#scroll-pane").height());
		
		//set up the slider
		$('#slider-vertical').slider({
			orientation: 'vertical',
			min: 0,
			max: 100,
			value: 100,
			slide: function(event, ui) {//used so the content scrolls when the slider is dragged
				var topValue = -((100-ui.value)*difference/100);
				$('#scroll-content').css({top:topValue});//move the top up (negative value) by the percentage the slider has been moved times the difference in height
			},
			change: function(event, ui) {//used so the content scrolls when the slider is changed by a click outside the handle or by the mousewheel
				var topValue = -((100-ui.value)*difference/100);
				$('#scroll-content').css({top:topValue});//move the top up (negative value) by the percentage the slider has been moved times the difference in height
			}
		});

		//set the handle height and bottom margin so the middle of the handle is in line with the slider
		$(".ui-slider-handle").css({height:handleHeight,'margin-bottom':-0.5*handleHeight});

		var origSliderHeight = $("#slider-vertical").height();//read the original slider height
		var sliderHeight = origSliderHeight - handleHeight ;//the height through which the handle can move needs to be the original height minus the handle height
		var sliderMargin =  (origSliderHeight - sliderHeight)*0.5;//so the slider needs to have both top and bottom margins equal to half the difference
		$(".ui-slider").css({height:sliderHeight,'margin-top':sliderMargin});//set the slider height and margins

	}//end if

	//code to handle clicks outside the slider handle
	$(".ui-slider").click(function(event){//stop any clicks on the slider propagating through to the code below
		event.stopPropagation();
	});

	$("#slider-wrap").click(function(event){//clicks on the wrap outside the slider range
		var offsetTop = $(this).offset().top;//read the offset of the scroll pane
		var clickValue = (event.pageY-offsetTop)*100/$(this).height();//find the click point, subtract the offset, and calculate percentage of the slider clicked
		$("#slider-vertical").slider("value", 100-clickValue);//set the new value of the slider
	});

	//additional code for mousewheel
	$("#scroll-pane,#slider-wrap").mousewheel(function(event, delta){
		var speed = 5;
		var sliderVal = $("#slider-vertical").slider("value");//read current value of the slider

		sliderVal += (delta*speed);//increment the current value

		$("#slider-vertical").slider("value", sliderVal);//and set the new value of the slider

		event.preventDefault();//stop any default behaviour
	});
});

function login(){
	var user = $('#frmLogin #user').val().trim();
	var pass = $('#frmLogin #pass').val().trim();

	if(user != '' || pass != ''){
		$.post('ajax.php', {action: 'login', user: user, pass: pass}, function(response){
			if(response == 'success'){
				$('#home img#tierra_nubes').fadeOut('fast', function(){
					$(this).remove();
					$('#home').remove();
				});
				$('#home div.divForm').fadeOut('fast', function(){
					$(this).remove();
					$("a.top.anchor").click();
					$('div#topContent').load('include.eventform.php');
				});
			}
			else{
				$('#home .message').html('Nombre de usuario o contraseña incorrectos').fadeIn('fast').delay('2000').fadeOut('fast');
			}
		}, 'text');
	}
}

function loadDefault(){
	$("a.top.anchor").click();
	$('div#topContent').load('include.eventform.php');
}

function deleteImage(image, form){
	if(confirm('¿Esta seguro de borrar esta imagen?')){
		$('li#' + image).fadeOut('fast', function(){
			$(this).remove();
			$('#' + form).prepend('<input type="hidden" name="imagesRemoved[]" value="' + image + '" />');
		});
	}
	
	return false;
}

function sendContactInfo(){
	var name = $('#frmContact #name').val().trim();
	var emp = $('#frmContact #empresa').val().trim();
	var mail = $('#frmContact #mail').val().trim();
	var lada = $('#frmContact #lada').val().trim();
	var phone = $('#frmContact #phone').val().trim();
	var msj = $('#frmContact div.nicEdit-main').html();
	
	$.post('ajax.php' , {action: 'send_contact_info', name: name, emp: emp, mail: mail, lada: lada, phone: phone, msj: msj}, function(response){
		alert(response);
		$('<p class="floatMessage">Su mensaje ha sido enviado. Gracias por escribirnos.</p>').insertAfter('#contact').css('opacity', 0).animate({top: '+=50', opacity: 1}, 1000).delay(2000).fadeOut('fast');
		if(response == 'success'){
			$('#frmContact #name').val('');
			$('#frmContact #empresa').val('');
			$('#frmContact #mail').val('');
			$('#frmContact #lada').val('');
			$('#frmContact #phone').val('');
			$('#frmContact #msh').val('');
			$('#frmContact div.nicEdit-main').html('');
		}
	}, 'text');
}

function getKey(e){
	tecla = (document.all) ? e.keyCode : e.which;
	//alert(tecla);
	if (tecla==9) return true;
	if (tecla==8) return true;
	if (tecla==46) return true;
	if (tecla>=35 && tecla <=39) return true;
	if (tecla>=96 && tecla <=105) return true;
	patron = /[0-9]/;
	return patron.test(String.fromCharCode(tecla));
}

function getEnterKey(evt){
	key = (document.all) ? evt.keyCode : evt.which;
	if(key == 13)
		login();
}

function saveImage(img, form){
	var tlwh = $('input[name="' + img + '"]').val().split(':');
	var top = tlwh[0];
	var left = tlwh[1];
	var width = tlwh[2];
	var height = tlwh[3];
	
	$('#' + form).prepend('<input type="hidden" name="images[]" value="' + imgName + '" />');
	$.post('ajax.php', {action: 'save_big_image', top: top, left: left, width: width, height: height}, function(response){
		if(response == 'success'){
			$('#bigImage').html('<p>Foto agregada</p>');
		}
		else{
			alert('Ha ocurrido un error. Por favor vuelva a agregar la imagen');
			$('#bigImage').html('');
		}
	}, 'text');
}

function saveImageGio(img, form){
	var tlwh = $('input[name="' + img + '"]').val().split(':');
	var top = tlwh[0];
	var left = tlwh[1];
	var width = tlwh[2];
	var height = tlwh[3];
	
	$('#' + form).prepend('<input type="hidden" name="images[]" value="' + imgName + '" />');
	$.post('ajax.php', {action: 'save_big_image_gio', top: top, left: left, width: width, height: height}, function(response){
		if(response == 'success'){
			$('#bigImage').html('<p>Foto agregada</p>');
		}
		else{
			alert('Ha ocurrido un error. Por favor vuelva a agregar la imagen');
			$('#bigImage').html('');
		}
	}, 'text');
}

function cancelSaveImage(){
	
}

function deleteEdecan(edecan){
	if(confirm('Se perderán todos los datos. De clic en Aceptar para continuar')){
		location.href="admin_edecanes.php?op=eliminar&id_edecan=" + edecan;
	}
}

function deleteEvent(event){
	if(confirm('Se perderán todos los datos. De clic en Aceptar para continuar')){
		location.href="admin_events.php?op=eliminar&id_evento=" + event;
	}
}

function deleteGio(gio){
	if(confirm('Se perderán todos los datos. De clic en Aceptar para continuar')){
		location.href="admin_gios.php?op=eliminar&id_gio=" + gio;
	}
}
