if(window.opener){
	//Add css for popups
	//Get a reference to css folder
	var cssLinks = $('head link');
	var cssFolder;
	
	for(var i = 0; i < cssLinks.length; i++){
		if(cssLinks[i].rel.toLowerCase() == 'stylesheet'){
			cssFolder = cssLinks[i].href.substring(0, cssLinks[i].href.lastIndexOf('/') + 1);
			break;
		}
	}
	
	
	var cssLink = document.createElement('link');
	cssLink.rel = 'stylesheet';
	cssLink.type = 'text/css';
	cssLink.href = cssFolder+'/interactive.css';
	document.getElementsByTagName('head')[0].appendChild(cssLink);
}

var videoData = new Array();
var index = 0;
var current;
var leftBuffer;
var rightBuffer;
var buffer;
var code;

//var h3ReplacementRegExp = /<h3\b[^>]*>(.*?)<\/h3>/gim;
var videoReplacementRegExp = /http:\/\/www.youtube.com\/v\/(.*?)&/gim;

function log(){
/*
	try{
		for(var i = 0; i < arguments.length; i++){
			console.log(arguments[i]);
		}
	}
	catch(e){}
*/
}

$().ready(function(){
	if($('#header-video').length > 0){
		setupVideoReel('#header-video');
	}
	
	if($('form').length > 0){
		setupForm();
	}
	
	setupLegalLinks();
	
	$('a[rel=external]').attr("target","_blank");
});


function setupVideoReel(root){
	$('#videos_list li').each(function(){
		var o = new Object();
		o.title = $(this).children('.title').html();
		o.code = $(this).children('.code').html();
		videoData.push(o);
	});

	//Get header image and use it to locate media root folder
	var images = document.getElementsByTagName('img');
	var imgSrc = images[0].src;
	var folder = imgSrc.substring(0, imgSrc.lastIndexOf('/') + 1);
	
//	var leftArrow = '<img id="header-left" src="'+folder+'left_arrow.gif" />';
	var leftArrow = '<a id="header-left"></a>';
	$('#header-container').prepend(leftArrow);
	
//	var rightArrow = '<img id="header-right" src="'+folder+'right_arrow.gif" />';
	var rightArrow = '<a id="header-right"></a>';
	$('#header-container').prepend(rightArrow);
	
	var next = '<div id="header-buffer"></div>';
	$('#header-canvas').append(next);
	
	code = $('#header-content').html();

	bindButtons();
}


function bindButtons(){
	$('#header-left').bind('click', nextVideo);
	$('#header-right').bind('click', prevVideo);
	$('#header-left').css('cursor', 'pointer');
	$('#header-right').css('cursor', 'pointer');
}

function unbindButtons(){
	$('#header-left').unbind('click', nextVideo);
	$('#header-right').unbind('click', prevVideo);
	$('#header-left').css('cursor', 'default');
	$('#header-right').css('cursor', 'default');
}

function setContainers(){
	if($('#header-buffer').css('display') == 'none'){
		current = $('#header-content');
		buffer = $('#header-buffer');
	}
	else{
		current = $('#header-buffer');
		buffer = $('#header-content');
	}
}

function writeBuffer(){
	var data = videoData[index];

//	var newCode = code.replace(h3ReplacementRegExp, '<h3>'+data.title+'</h3>');
	var newCode = code.replace(videoReplacementRegExp,'http://www.youtube.com/v/'+data.code+'&');
	
	$('#header-canvas h3').html(data.title);
	
	buffer.html(newCode);
}

function hideCurrent(){
	$(current).css('display', 'none');
}

function nextVideo(){
	unbindButtons();
	setContainers();
	
	index++;
	
	if(index >= videoData.length){
		index = 0;
	}
	
	writeBuffer();
	

	$(buffer).css('display', 'block');
	$(buffer).css('left', '640px');


	$(current).animate(
		{
			left: '-=640px'
		},
		1000,
		hideCurrent
	);

	$(buffer).animate(
		{
			left: '0px'
		},
		1000,
		bindButtons
	)

	
	
}

function prevVideo(){
	unbindButtons();
	setContainers();
	
	index--;
	
	if(index < 0){
		index = videoData.length - 1;
	}
	
	writeBuffer();
	
	$(buffer).css('display', 'block');
	$(buffer).css('left', '-640px');


	$(current).animate(
		{
			left: '640px'
		},
		1000,
		hideCurrent
	);

	$(buffer).animate(
		{
			left: '0px'
		},
		1000,
		bindButtons
	)	
	
}


/* FORMS */
function setupForm(){
	$('#send').bind('click', checkForm);
}

function checkForm(){
	
	if($('#errorCanvas').length > 0){
		$('#errorCanvas').html('');
	}
	
	var errors = new Array();

	if($('#firstName').val().length == 0){
		errors.push('nos indiques tu nombre');
	}

	if($('#lastName').val().length == 0){
		errors.push('nos indiques tu apellido');
	}
	
	var filter = /^([\w\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
	
	if(!filter.test($('#email').val())){
		errors.push('nos indiques tu e-mail');
	}
	
	if($('#phoneNumber').val().length == 0){
		errors.push('nos indiques un tel&eacute;fono de contacto');
	}	
	
	var isVideoForm = ($('#url').length > 0);
		
	if(isVideoForm){
		
		filter = /^http:\/\/(www\.|[a-z]{2}\.)?youtube\.com\/watch\?v=([^&]+)/;
		
		if(!filter.test($('#url').val())){
			errors.push('nos indiques su url en Youtube');
		}	
		
		if($('#title').val().length == 0){
			errors.push('nos indiques su t&iacute;tulo');
		}	
		
		if(!$('#legal')[0].checked){
			errors.push('marques la casilla confirmando que tienes los derechos del vídeo');
		}
	}
	else{
		if($('#text').val().length  == 0){
			errors.push('rellenes el campo &quot;Escribe tu pregunta&quot;');
		}
	}
	
	var model = $('#phoneModel');
	
	if(model.length == 0){
		model = $('#model');
	}
	
	if(model.val().length == 0){
		errors.push('nos indiques el modelo de tu m&oacute;vil');
	}	
	
	if(errors.length == 0){
		return true;
	}
	else{
		
		var intro = (isVideoForm) ? 'Para poder compartir tu v&iacute;deo es necesario que:' : 'Para poder enviarnos tu pregunta es necesario que:';
		
		var errorsHtml = '<p>'+intro+'</p>';
		errorsHtml += '<ul class="errorMessage">';
		
		for(var i = 0; i < errors.length; i++){
			errorsHtml += '<li><span>'+errors[i];
			if(i < errors.length - 1){
				errorsHtml += ',';
			}
			else{
				errorsHtml += '.';
			}
			
			errorsHtml += '</span></li>';
		}
		
		errorsHtml += '</ul>';
		
		if($('#errorCanvas').length == 0){
			$('form').before('<div id="errorCanvas"></div>');
		}

		$('#errorCanvas').html(errorsHtml);
		
		return false;
	}
}

/* LEGAL LINKS */
function setupLegalLinks(){
	$('#footer p a').each(function(){
		if(this.href.indexOf('mailto:') < 0){
			$(this).bind('click', openLegal)
		}
	});

	$('#upload-form a').each(function(){
		if(this.href.indexOf('mailto:') < 0){
			$(this).bind('click', openLegal)
		}
	});	
	
}

var pop;

function openLegal(e){

	var url = e.currentTarget.href;
	
	if(pop){
		try{
			pop.close();
		}
		catch(e){}
		
		pop = null;
	}
	
	pop = openPopup(url, 'legalWin', 400, 600)
	return false;
}


function openPopup(url, name, w, h, x, y, _scroll){
	var wW = (w!=null) ? w : screen.width - 50;

	var wH = (h!=null) ? h : screen.height - 150;

		

	var wX = (x!=null) ? x : Math.round(screen.width / 2 - (wW / 2));

	var wY = (y!=null) ? y : Math.round(screen.height / 2 - (wH / 2));

    

    var name = (name != null) ? name : 'dyPopup';

    

    var scrollbar = (_scroll != null) ? _scroll : 1;



    var win = window.open(url, name, 'resizable=0,scrollbars='+scrollbar+',status=0,location=0,toolbar=0,menubar=0,width='+wW+',height='+wH+',screenX='+wX+',screenY='+wY+',left='+wX+',top='+wY+'');



    return win;

}

